$nama = array('a' => 'John', 'b' => 'James', 'c' => 'Ray', 'd' => 'Lime', 'e' => 'Kit');

//sort ($nama);
//reset($nama);
   
$i=1;
do
      {
      echo "The key is " .$i. " and the value is " .$nama[$i];
	  $i++;
	  }	  
while ($i<=5);	
Echo "newline";
 
?>

The following error appears:

Notice: Undefined offset: 1 in C:\xampp\htdocs\php_exercise\exercise3.php on line 12
The key is 1 and the value is
Notice: Undefined offset: 2 in C:\xampp\htdocs\php_exercise\exercise3.php on line 12
The key is 2 and the value is
Notice: Undefined offset: 3 in C:\xampp\htdocs\php_exercise\exercise3.php on line 12
The key is 3 and the value is
Notice: Undefined offset: 4 in C:\xampp\htdocs\php_exercise\exercise3.php on line 12
The key is 4 and the value is
Notice: Undefined offset: 5 in C:\xampp\htdocs\php_exercise\exercise3.php on line 12
The key is 5 and the value is newline

Any clue? Thanks.

Member Avatar for diafol

try this:

$nama = array('a' => 'John', 'b' => 'James', 'c' => 'Ray', 'd' => 'Lime', 'e' => 'Kit');
 $x=0;
foreach($nama as $key => $val)
      {
      echo "The key is " .$key. " and the value is " .$val . "<br />";
	  echo "The key is " .$x. " and the value is " .$val . "<br />";
	  $x++;
	  }

the counter is just there to show how you can count up - the key is 'a' for the first one,... etc
If you don't want a specific key, just use:

$nama = array('John','James','Ray','Lime','Kit');
foreach($nama as $key => $val){
      echo "The key is " .$key. " and the value is " .$val . "<br />";
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.