Kevin Karl Leaño
Kevin Karl Leaño

Reputation: 1800

Get key using array_search in multidimensional array

I have to get the array key name using array_search but it gives me 0 and 1 rather than "login" or "home"

this is my code

  $PAGINATOR = array("login" => array("permission" => false,
                                  "auth"           => false,
                                  "title"          => "Login",
                                  "slug"           => "?id=login",
                                  "layout"         => "pages/login.php",
                                  "default"        => true),
                 "home"  => array("permission"     => false,
                                  "auth"           => true,
                                  "title"          => "Home",
                                  "slug"           => "?id=home",
                                  "layout"        => "pages/home.php",
                                  "default"       => false));

array_search(true, array_column($PAGINATOR, 'default'))

Upvotes: 0

Views: 257

Answers (1)

Thamilhan
Thamilhan

Reputation: 13313

array_column just gives numeric keys for the column selected when only column_key is sent. You need a work around instead:

array_search(true,(array_combine(array_keys($PAGINATOR), array_column($PAGINATOR, 'default'))));

Check EVAL


Explanation:

After returning values from a single column, fetch the keys of the original array using array_keys. Then using array_combine combine the keys and values.


Step by step:

$a = array_column($PAGINATOR, 'default');

$b = array_keys($PAGINATOR);

$c = array_combine($b,$a);

$d = array_search(true,$c);

print_r($a);
print_r($b);
print_r($c);
print_r($d);

Prints:

Array
(
    [0] => 1
    [1] => 
)

Array
(
    [0] => login
    [1] => home
)

Array
(
    [login] => 1
    [home] => 
)

login

Upvotes: 1

Related Questions