PHP equivalent to C#'s multi-dimensional array declaration - c#

In C# you can do this:
poules = new int[aantal, aantal, 2];
I couldn't find a way in PHP to do this. All I can find is a two dimensional array.

The example you presented is creating a 3D array, and getting it by a method (which is a bit slower, since a method is used). PHP uses jagged arrays.
An array in PHP is created using the array function.
To match your example: (for fixed array length)
$myArr = new SplFixedArray($aantal);
for ($i = 0; $i < $aantal; $i++) {
$myArr[$i] = new SplFixedArray($aantal);
for ($j = 0; $j < $aantal; $j++) {
$myArr[$i][$j] = new SplFixedArray(2);
}
}
SplFixedArray is used to define an array with a fixed size.
As claimed in comments, you will rarely see a PHP code as the above.
you can access the array cells like this:
$val = $myArr[$x][$y][$z];
Here is a reference: SplFixedArray

I'm not a C# person, so take this with a grain of salt. After perusing the documentation though, new int[aantal, aantal, 2] seem to be the syntax to declare multi-dimensional int arrays, in this case a 3-dimensional array.
PHP doesn't have multi-dimensional arrays. It only has arrays, and you can have arrays of arrays. I guess this is called a "jagged array" in C#. PHP arrays are also not typed, there's no equivalent to int[].
You can simply declare/access several dimensions at once though:
$arr = array();
$arr[1][2][3] = 'foo';
PHP will create the intermediate arrays as needed. The array is jagged though, there's no $arr[0][2][3] after the above code executed.
If you need to pre-allocate all dimensions beforehand, you will have to recursively loop. This is not really something done very often in PHP though, you should adapt your practices to work with jagged arrays to get things done.

This would be a php array:
$poules = array('aantal', 'anntal', '2');
In case aantal is a variable, just the same without quotes:
$poules = array($aantal, $anntal, '2');
In PHP you don't need to specify the variable type. Although you can use it to validate or filter inputs.
You can read more about PHP arrays in the official documentation:
http://uk3.php.net/manual/en/language.types.array.php

$poules = array('aantal', 'aantal', 2);
Or are aanta1 arrays too? Because in php you can do:
$myArray = array("some data", array("more data", "in a other array"), array("key1" => "even with keys"));

Related

Assign string array to two dimensional string array

I'm a little bit confused. I try to assign a string array to a two dimensional string array. But get "Wrong number of indices" error.
I understand the error, but should it not be possible to assign an array to the second dimension array field?
As sortedString has x number of fields with each an string array, should it not be possible to assign an string array to just a indexed field? (as the s.Split(';') already creates an array)
string[,] sortedString = new string[count,columns];
sortedString[counter] = s.Split(';');
You're confusing a multidimensional array with a jagged array. sortedString is a 2-dimensional array of type string, so you must always provide the correct number of indices - in this case, 2. You can't say sortedString[x], you can only say sortedString[x, y].
You're probably thinking of a jagged array - i.e., a single-dimensional array, where each element is itself a (usually single-dimensional) array. Declare sortedString like this:
string[][] sortedString = new string[count][];
This will allow each "inner" array to be of a different length (depending on how many ; there are in each s), which might not be what you want.
C# has two kinds of 2D arrays. If you need access to one dimension at a time as it's own array, you must use the "jagged" variety, like this:
string[][] sortedString = new string[count][];
for(int i = 0; i<sortedString.Length;i++)
sortedString[i] = new string[columns];
Or, even better:
var sortedString = new List<string[]>;

Storing an array of references to arrays

I want to create an array of references to my arrays. The reason for this is because i want to optimise my fast Fourier transform algorithm to be branchless - or rather, less branchy.
The idea behind it is i have two arrays:
Array1 and Array2
I need to ping pong between the two in a for loop so i want to store the reference to the arrays like this:
[0] = Array1Ref
[1] = Array2Ref
[2] = Array1Ref
. . .
Is it possible to do this in C#? If so how would you define such an array - would i need to use unsafe ?
If you just want to access a different array in each iteration of the for loop without using a conditional, you can keep swapping two variables and use one of them.
var arrayRef = Array1;
var theOtherArrayRef = Array2;
for (...) {
// use arrayRef in places where you would have accessed the array of array references
...
// C# 7 tuple syntax
(arrayRef, theOtherArrayRef) = (theOtherArrayRef, arrayRef);
// pre-C# 7:
/*
var temp = arrayRef;
arrayRef = theOtherArrayRef;
theOtherArrayRef = arrayRef;
*/
}

C# Adding and Removing elements to an array with an existing size

I just have a question. I noticed that unlike C++, C# is a bit complicated when it comes to array. One of the features or techniques I've been looking for in the array is that: I want to add elements or remove elements from it in a more efficient and simpler way.
Say for example, I have an array called 'food'.
string[] food = {'Bacon', 'Cheese', 'Patty', 'Crabs'}
Then I decided to add more food. Problem with C# as I can see it is this isn't possible to do unless you do use an ArrayList. How about for an array itself? I want to use the array as some sort of inventory where I add things.
Thanks a lot!
You can't do that with arrays in C# without allocating a new array. Because arrays are fixed in size.
If you want to be able to add/remove elements from a container, you could use List<T>. Alternativly you could use an ArrayList but that is not recommended, since in most cases List<T> has a performance advantage.
Internally both use an array as the default container for your data. They also take care of resizing the container according to how much data you put in the collection or take out.
In your example, you would use a list like
List<string> food = new List<string> { "Bacon", "Cheese", "Patty", "Crabs" };
food.Add("Milk"); //Will add Milk to the list
food.Remove("Bacon"); //Will remove "Bacon"
List on MSDN: Docs
Ideally, if you are going to have a variable size array of strings, a List would be better. All you would have to do is then call list.Add(""), list.Remove(""), and other equivalent methods.
But if you would like to keep using string arrays, you could create either a function or class that takes an array, creates a new array of either a larger or smaller size, repopulate that array with the values you had from the original array, and return the new array.
public string[] AddFood(string[] input, string var)
{
string[] result = new string[input.Length + 1];
for (int i = 0; i < input.Length; i++)
{
result[i] = input[i];
}
result[result.Length - 1] = var;
return result;
}
public string[] RemoveFood(string[] input, int index)
{
string[] result = new string[input.Length - 1];
for (int i = 0; i < input.Length; i++)
{
if (i < index) {
result[i] = input[i];
}
else
{
result[i] = input[i + 1];
}
}
return result;
}
Again, I would highly recommend doing the List method instead. The only down side to these lists is that it appends them to the end, rather then figuring out where you want to place said items.
List<string> myFoods = new List<String>(food);
myFoods.Add("Apple");
myFoods.Remove("Bacon");
myFoods.AddRange(new string[] { "Peach", "Pineapple" });
myFoods.RemoveAt(2);
Console.WriteLine(myFoods[0]);
There is also ArrayList if you want a list more like an array, but it is older code and unfavoured.
ArrayList myFoods = new ArrayList(food);
myFoods.Add("Apple");
myFoods.Remove("Bacon");
myFoods.AddRange(new string[] { "Peach", "Pineapple" });
myFoods.RemoveAt(2);
Console.WriteLine(myFoods[0]);
I hope this helps.
To actually answer the question, you just need to resize the array.
Array.Resize(ref array, );
is the new length of the array
To really add elements to an existing array without resizing you can't. Or, can you? Yes, but with some trickery, which at some point you might say is not worth it.
Consider allocating an array of the size you anticipate it could be. You obviously have to estimate well to avoid tons of unused space. Empty slots in the array would be marked by a sentinel value; for a string the obvious candidate is null. You'd know the "true" size of the array by keeping track of the first index of the sentinel. This suggests that an ArrayWrapper class would encapsulate the array and "true size".
That wrapper could add Add() and AddRange() that replace the sentinel values with real ones without allocating.
All that said, the drawback at some point will be that you have to allocate a new array. Doing this manually using the wrapper is pointless unless you have very specific requirements that allow you to reduce allocations.
So, for the most common cases, stick to a List<>, which does that for you. With the list you can construct it by calling the constructor that takes an initial capacity parameter. Adds will use the underlying array without reallocation until it hits the limit.
In a way that List<> is your wrapper that uses an allocation model the original authors decided would minimize allocations in most cases. That is likely to perform better than anything you write unless you can really leverage your domain.

Confusion using SimpleJSON - JSON interpretor

I'm using SimpleJSON which can be found here. <-- Source and documentation.
Here's the JSON that's being output in my PHP script using the json_encode function.
{
"response":3,
"establishments":[
["1","-107.102180","39.410870","0"],
["8","-106.977715","39.377403","7.03707478751404"],
["9","-106.843636","39.484631","14.706647410396497"],
["12","-106.950661","39.230804","14.846070600598637"]
]
}
In the examples on the SimpleJSON page, "establishments" should technically be a nested object, and not a nested array. After going through the code I had assumed that the following would suffice
int id = N["establishments"][0].Value
double long = N["establishments"][1].Value
double lat = N["establishments"][2].Value
Where N is the node containing the Json Information (more info in docs).
However all of these values are returning blank, could anyone point out why? So far arrays have been my only problem with this, and I don't understand the logic behind this enough to figure out what's wrong on my own.
NOTE: As pointed out by #jskidie this is a two dimensional array, I'm having problems returning the full Array (in the 2nd dimension) not the values.
Because you have multi dimensional array. Try:
int id = N["establishments"][0][0].Value
double long = N["establishments"][0][1].Value
double lat = N["establishments"][0][2].Value
What I was looking for was stored in the JSONArray class.
JSONArray array = json["establishments"].AsArray;
for(int i = 0; i < array.Count; i++) {
}
which allows me to iterate over all occurrences.

How to access second Dimension of Array [duplicate]

This question already has answers here:
Two dimensional array slice in C#
(3 answers)
Closed 8 years ago.
Following situation:
I have a Array which got 2 dimension. No i want to access the second dimension. How can i achieve this goal?
Here my code to clarify my problem:
private static int[,] _Spielfeld = new int[_Hoehe, _Breite];
private static bool IstGewonnen(int spieler)
{
bool istGewonnen = false;
for (int zaehler = 0; zaehler < _Spielfeld.GetLength(0); zaehler++)
{
//Here i cant understand why compiler doesnt allow
//Want to give the second dimension on the Method
istGewonnen = ZeileSpalteAufGewinnPruefen(_Spielfeld[zaehler] ,spieler);
}
return istGewonnen;
}
//This method want to become an Array
private static bool ZeileSpalteAufGewinnPruefen(int[] zeileSpalte, int spieler)
{
//Some further code
}
The compiler is saying: "Argument from type int[,] is not assignable to argument of type int[]. In Java it is working as i expected. Thanks in advance.
Define your array as a jagged array (array of arrays):
private static int[][] _Spielfeld = new int[10][];
Then loop through the first dimension and initialize.
for (int i = 0; i < _Spielfeld.Length; i++)
{
_Spielfeld[i] = new int[20];
}
Then the rest of your code will compile OK.
C# allows two different offers two flavors of multidimensional arrays which, although they look quite similar, handle quite differently in practice.
What you have there is a true multidimensional array, from which you cannot automatically extract a slice. That would be possible (as in Java) if you had a jagged array instead.
If the choice of having a multidimensional array is deliberate and mandatory then you will have to extract slices manually; for example see this question.
If the choice between jagged and multidimensional is open then you can also consider switching to a jagged array and getting the option of slicing for free.

Categories