foreach inside foreach how do i call variables

advertisements

How can I prevent the value of $key in first loop but I need to call the $key in the second loop? The value of $key in 1st loop is different to the 2nd loop

<?php
$variables = array('ABC' => array('A', 'B', 'C'), 'DEF' => array('D', 'E'));
foreach ($variables as $key => $values){
      echo $key; //the value of $key in first loop is different to the second loop
      foreach($values as $value){
           echo $key; //I want the value of $key is still the value in first loop
      }
}
?>


I would suggest you to do something like this:

<?php
$variables = array('ABC' => array('A', 'B', 'C'), 'DEF' => array('D', 'E'));
foreach ($variables as $key => $values){
    foreach($values as $value){
        // Here you can access every variables previously declared
        echo '<div id='$key' class='$value'>test</div><br />';
    }
}

What you were trying to do is to access a variable that you were only declaring later (in the foreach loop). Keep in mind that you can access a variable if it's in the same environment.