dmgd
dmgd

Reputation: 445

I can't compare associative array indexes to a var

I can not figure out how to compare the array index. I know this has to be simple.

$list_array array (
  'first' => array('one' => 1, 'two' => 2),
  'second' => array('one' => 3, 'two' => 4)
);

foreach ($list_array as $key) {
  if(<the-list_array-index> == 'second' ) {
   echo $key['one']. ' - '. $key['two'];
  }
 }

result 3 - 4

Upvotes: 0

Views: 94

Answers (2)

ComFreek
ComFreek

Reputation: 29424

Use this syntax:

foreach ($array as $key => $value)

foreach ($list_array as $index => $key) {
    if($index == 'second' ) {
      echo $key['one']. ' - '. $key['two'];
    }
}

One suggestion though: Rename $key to an appropriate and meaningful name in your context!

If you do not find any or if your function works with arrays in general, use $value since this term is very well-known among developers:

foreach ($list_array as $index => $value) {
    if($index == 'second') {
      echo $value['one'] . ' - ' . $value['two'];
    }
}

Consider u_mulder's answer below if you just want to directly access the key. As far as I can see in your code, a loop is unnecessary.

Upvotes: 3

u_mulder
u_mulder

Reputation: 54841

if (array_key_exists('second', $list_array))
    echo $list_array['second']['one'] . ' - ' . $list_array['second']['two'];

Upvotes: 0

Related Questions