Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.