Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Get array value with a numeric index

I have an array like:

$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum'); echo native_function($array, 0); // bar echo native_function($array, 1); // bin echo native_function($array, 2); // ipsum 

So, this native function would return a value based on a numeric index (second arg), ignoring assoc keys, looking for the real position in array.

Are there any native function to do that in PHP or should I write it? Thanks

like image 321
thom Avatar asked Jun 18 '11 13:06

thom


People also ask

How do you get the value of a particular index of an array in PHP?

We can get the array index by using the array_search() function. This function is used to search for the given element.

How do you get a specific value from an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

How do you find the index of an associative array?

The elements of an associative array can only be accessed by the corresponding keys. As there is not strict indexing between the keys, accessing the elements normally by integer index is not possible in PHP. Although the array_keys() function can be used to get an indexed array of keys for an associative array.


1 Answers

$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum'); $array = array_values($array); echo $array[0]; //bar echo $array[1]; //bin echo $array[2]; //ipsum 
like image 93
genesis Avatar answered Oct 10 '22 00:10

genesis