phparraysmultidimensional-arrayfilter

php array_column with unsequential index returns wrong index


So I have an array in php like this:

array(
  22 => array()
  23 => array()
  25 => array()
)

I am using array_column in search_array to search a column in the sub arrays.

$index=array_search('needlehere',array_column(myarray,'columnbeingsearchedhere'))

But the array_column is not using the correct indexes, but reindexing them to be 0,1,2...

Is there anyway to keep the correct indexes?


Solution

  • array_column() doesn't maintain indexes (although it allows you to set your own from other data columns in the row), but you can handle that using something like:

    array_combine(
        array_keys($myarray),
        array_column($myarray,'columnbeingsearchedhere')
    );
    

    EDIT

    Alternative, that probably grabs a bit more memory temporarily (unless you don't mind the original array being modified), but might be a bit faster overall (depending on your data):

    $newArray = $myArray;
    array_walk($newArray, function(&$value) use ($columnName) { $value = $value[$columnName]; } );