简体   繁体   中英

How to get the key of a requested item in an array?

This is the method I use to find the key of a requested item in an array,

$items = array
(
    '0' => array
        (
            'mnu_id' => '1',
            'pg_url' => 'home'
        ),

    '1' => array
        (
            'mnu_id' => '5',
            'pg_url' => 'about'
        ),

     '2' => array
        (
            'mnu_id' => '6',
            'pg_url' => 'venues'
        )

);

So if I request the value of 'venues',

while ($current = current($items)) 
{
    if ($current['pg_url'] == 'venues') {
        $current_key = key($items);
    }
    next($items);
}

echo $current_key;

I get the key which is 2.

I don't really like this method as it is a bit lengthy and it confuses me when using while() to loop the array. I don't understand why I have to use next() in the code too!

I wonder if there are any better method than this to get the key?

foreach (array_keys($items) as $key) {
  if ($items[$key]['pg_url'] == 'venues') {
    $current_key = $key;
    // optionally use a break here to escape the loop
  }
}

Maybe this is a little easier to understand:

$current_key = -1;
foreach($items as $key => $item) {
  if($item['pg_url'] == 'venues') {
    $current_key = $key;
  }
}

I don't know, what exactly you are trying to do, but it seems like you want to retrieve information from the array depending on the pg_url... if so, maybe it would be nicer to set the pg_url as key:

$items = array
(
    'home' => array
        (
            'mnu_id' => '1'
        ),

    'about' => array
        (
            'mnu_id' => '5'
        ),

    'venues' => array
        (
            'mnu_id' => '6'
        )

);

then you could simply check for

if(isset($items['venues'])) ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM