PHP - Using foreach to Loop Through Keys and Values

Introduction

To use foreach to retrieve both keys and values, use the following syntax:

foreach ($array as $key =>  $value) {
    // (do something with $key and/or $value here
}
// (rest of script here)

The element's key is stored in the $key variable.

You can use any variable names you like; they don't have to be $key and $value.

Demo

<?php

           $myBook = array("title"=> "Java",
                           "author"=> "John A",
                           "pubYear"=>  2018);

           foreach ($myBook as $key =>  $value) {
             echo"< dt > $key < /dt >";
             echo"< dd > $value < /dd >";
           }//from  ww w.  j a  v a 2s  .co  m

?>

Result

Related Topic