Dean219 Dean219 - 3 months ago 10
PHP Question

Value from php array seems incorrect

Im having an issue with understanding why my array containing 3 elements must be sliced into 2 parts each. I wish to access a number im pushing into the array only however it seems to print out the index rather than the 'key' value i pushed into it ($number).

I have a 2d array im pushing an ID and an integer into, and then sort it :

$array = [[]];
array_push($array, $doc[_id], $number);
array_multisort($array);


I then filter any empty elements:

$array = array_filter($array); //remove null elements


This all works as id expect however the array looks like this by this point:

unrated.array(5)
{
[2]=> object(MongoId)#32 (1)
{ ["$id"]=> string(24) "57b99696ce2350100b000029" }

[3]=> object(MongoId)#31 (1)
{ ["$id"]=> string(24) "57b998ccce2350181700002b" }

[4]=> object(MongoId)#33 (1)
{ ["$id"]=> string(24) "57b99a84ce2350100b00002b" }

[5]=> int(2) [6]=> int(3)

}


Again, this is fine however it means when i loop over the array using the code below it appears to be longer than 3 elements, as i have to slice from 0-6 instead of 0-3:

$array = array_slice($array, 0, 6, true); //only get 3 elements from array
foreach ($array as $key => $value) {
echo $key; //prints out values from 1-5 weirdly.... should just print the $number value
$id = $value->{'$id'};
}


What im trying to achieve is to find the element in the array with the lowest possible value that was pushed earlier (array_push($array, $doc[_id], $number);) however because i cannot understand why the array is split into 6 rather than 3 parts its even more confusing.

Question in short : how do i access the $number pushed into the array and why is my array 6 seemingly 6 in size when it contains only 3 elements.

Any help would be appreciated, thanks.

Answer

To be clear, array_push simply pushes one or more values onto the end of an array. The first argument of array_push is the array you wish to push the value(s) to, and any subsequent argument is a list of values you wish to push. So what you're doing with array_push($array, $doc[_id], $number) is pushing two values ($doc[_id] and $number) to the end of the array $array. array_push will just use the next available index as the key when it adds those values to the array. It will not allow you to specify a key. This is the same thing as doing $array[] = $value.

To specify a key you must assign a value directly to the array key like so: $array[$key] = $value.

Comments