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
We can get the array index by using the array_search() function. This function is used to search for the given element.
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.
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.
$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum'); $array = array_values($array); echo $array[0]; //bar echo $array[1]; //bin echo $array[2]; //ipsum
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With