Skip to content
Advertisement

PHP mixed associative array how to get values in foreach loop

Well I have something like

$Arr1 = array("a1" => array("a1b", "a1b"),
              "a2" => array("a2b", "a2b"),
              "a3",
              "a4",
              "a5" => array("a5b", "a5b")
);

meaning that “a3” and “a4” are keys without values.

I need to go through a foreach loop to get $key => $value pairs.

Should be something with checking of isset($value) but it doesn’t work.

UPDATE: Question is closed. Thanks to all. As it was written key without value is not a key, but value with a default integer key. So if anyone wants to use the structure above make this

 foreach ($Arr1 as $key => $value) { 
      if (is_int($key)) { 
           $key = $value; 
           $value = null; 
      } 
      //use $key and $value
 }

Advertisement

Answer

Each element of an array has a key. “a3” and “a4” aren’t keys, they are elements which have numeric keys. You make sure it if you make var_dump of this array

array (size=5)
  'a1' => 
    array (size=2)
      0 => string 'a1b' (length=3)
      1 => string 'a1b' (length=3)
  'a2' => 
    array (size=2)
      0 => string 'a2b' (length=3)
      1 => string 'a2b' (length=3)
  0 => string 'a3' (length=2)
  1 => string 'a4' (length=2)
  'a5' => 
    array (size=2)
      0 => string 'a5b' (length=3)
      1 => string 'a5b' (length=3)

You can get elements with numeric keys with array_filter function and checking of key type (for example with help is_int function)

$arr = array(
    "a1" => array("a1b", "a1b"),
    "a2" => array("a2b", "a2b"),
    "a3",
    "a4",
    "a5" => array("a5b", "a5b")
);

$newArr = array_filter($arr, function($key) {
    return is_int($key);
}, ARRAY_FILTER_USE_KEY);

or foreach statement:

$arr = array(
    "a1" => array("a1b", "a1b"),
    "a2" => array("a2b", "a2b"),
    "a3",
    "a4",
    "a5" => array("a5b", "a5b")
);

$newArr = [];
foreach ($arr as $key => $value) {
  if (is_int($key)) {
      $newArr[] = $value;
  }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement