1

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?

3
  • array_column is used to get the common index columns.... Commented May 17, 2016 at 7:47
  • array_combine workaround won't work if some of the subsets in your array don't have the specified column(array_column will dump those instead of return NULL). Commented Feb 23, 2017 at 9:59
  • Most directly, use array_find_key(): Get the first level key of the first row containing a specified column value in a 2d array Commented Mar 19 at 8:11

1 Answer 1

3

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]; } );
Sign up to request clarification or add additional context in comments.

3 Comments

this is a possible work around but i guess the overhead would be a lot more and might just be worth doing a simple loop through.
The comment of PixelPaul has to be promoted to answer because doing a loop seems the only meaningful way to address the problem!
See array_map() on the dupe target -- that's what I would use for this task.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.