0

Using PHP's website as a reference I'm trying to search for a key of the known value in associative array:

http://php.net/manual/en/function.array-search.php

The following code always returns 1, but suppose to return 120:

$location_key = array_search(1, array_column($locations, 'main'));

print_r($locations):

Array
(
    [120] => Array
        (
            [clientid] => 122103
            [name] => HQ
            [address] => 2013 BENSON GARDEN BLVD
            [address2] => 
            [city] => OMAHA
            [state] => NE
            [zip] => 68134
            [country] => UNITED STATES
            [lat] => 00.000
            [lng] => -0.0000
            [taxrate] => 0
            [main] => 1
            [active] => 1
            [contactid] => 14
        )

    [122] => Array
        (
            [clientid] => 122103
            [name] => Branch
            [address] => 515E E 72ND ST
            [address2] => 
            [city] => NEW YORK
            [state] => NY
            [zip] => 10021
            [country] => UNITED STATES
            [lat] => 40.766705
            [lng] => -73.952965
            [taxrate] => 0
            [main] => 0
            [active] => 1
            [contactid] => 0
        )

)

Not sure why PHP's website is referencing the highest up voted "User Contributed Note" which doesn't work.

1
  • Rather than post the same advice twice, see this on the dupe target. Commented Jan 18 at 12:37

1 Answer 1

1

This is because array_column() doesn't keep your keys. So you first need to array_combine() the keys with the array from array_column(), e.g.

$location_key = array_search(1, array_combine(array_keys($locations), array_column($locations, 'main')));
Sign up to request clarification or add additional context in comments.

4 Comments

Totally makes sense... Just wonder how come the answer from xfoxawy at gmail dot com on PHP's site has 235 votes with exactly same structure like mine and it doesn't work.
@AlexG Look at it closely again :) He doesn't have an associative array like you have. His one is 0,1,2,...
Hmmm.... 0,1,2 (in order) makes it an associative array compare to mine 120,122 ... ?
@AlexG It's an enumerated array starting from 0 as ever array does. Same as array_column(), so that is why they match up with the keys. (Do: print_r(array_column(...));)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.