Jump to content

[SOLVED] for each loop ??


ali_2kool2002

Recommended Posts

hi can someone tell me how a for each loop works in english like as i dont understand this line?

 

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

where does key come from and value?? i understand x is  a variable storing an array?

 

the full code is below:

<?php

if($_POST['submit']){
echo $key;
}

$x=array("a" => "a was seleted" , "b" => "b was selected" , "c"  =>  "c was selected");

echo"<form method='POST' action=''>";

foreach ($x as $key => $value){

echo"<input type='radio' name='key' value='$value'>$key<br>";
}
echo"<br><input type='submit' name='submit' value='GET ME'>";

?>

Link to comment
https://forums.phpfreaks.com/topic/42013-solved-for-each-loop/
Share on other sites

foreach is a loop that walks throw an array.

 

you set a array

 

example

 

$a=array("1","2","3");

 

now the array is a single array set with numbers using the foreach

we walk throw the array.

 

foreach($a as $x){

 

echo $x;

}

now the array get's all that in $a as $x we set the $a as $x to get

foreach to loop throw the array.

 

$x is also known as the value becouse we got all the array values.

 

 

now we set another array but this array has key's and values

 

$a=array("a" => "1", "b" => "2", "c" => "3");

 

what we have done is made a array that has keys a b c and told the

array that => abc are now got values of 123 so when we foreach we need the foreach to no that.

 

so foreach

 

foreach($a as $key => $value){

 

echo " $key <br> $value <br>";

 

}

 

now as you can see we set $a as $key abc and the value as 123

 

hope that helps.

Link to comment
https://forums.phpfreaks.com/topic/42013-solved-for-each-loop/#findComment-203744
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.