So I have the following, working code:
$arrayitertest=Array("Fruit"=>Array("Pear","Peach","Apple","Banana"),"Cars"=>Array("My budget","other cars."));
foreach ($arrayitertest as $key=>$value)
foreach($arrayitertest[$key] as $result) echo $key.":". $result."|";
But when I change foreach ($arrayitertest as $key => $value) to foreach ($arrayitertest as $key) it throws a fatal error (despite the fact I never use the $key variable.)
The Error is:Invalid argument supplied for foreach() in
Could someone be so kind as to tell me why that happens ?
Edit: Wow, thanks for all the answers.... I will give the accept to the most specific one as of this moment though.
As far as your error is concerned: If you remove the $value from the first foreach, $key becomes the value and $arrayitertest[$key] becomes "pear" which is an invalid argument for the second foreach.
Your program would halt on:
// this is not going to work
foreach ("pear" as $result)
If you don't need the key of the first foreach you can just change it to:
foreach ($arrayitertest as $value)
{
foreach($value as $result)
{
}
}
I think you are misunderstanding the order of key and values. Where you say $value => $key it's technically $key => $value.
The way to parse your array is this:
foreach ($array as $key => $value) {
foreach ($array[$key] as $v) {
// $v = Pear (1st iteration), Peach (2nd), Apple (3rd) ... (for key = Fruit)
// $v = My Budget (1st iteration), other cars. (2nd) (for key = Cars)
// notice that $key is also accessible here
}
}
Obviously if you don't need the $key either you can simply:
foreach ($array as $a)
foreach ($a as $v)
// use $v here
Coding $value => $key, puts Fruit, Car, ... into $value.
Coding just $value puts the arrays such as Array("Pear","Peach","Apple","Banana") into $value and that is not a valid index for an array.
Related
All the answers I've found only talk about unsetting $value except one, which wasn't clear to me. So here I am. Say I have the line:
foreach ($data as $key => $value)
{
// do stuff
}
Should I put these two lines after?
unset($key);
unset($value);
Or can I omit unset($key)? Also, is it recommended to ALWAYS use unset after every foreach? Say I have nested foreach loops, like this:
foreach ($data as $key => $value)
{
foreach ($data[$key] as $key => $value)
{
// do stuff
}
unset($key);
unset($value);
}
unset($key);
unset($value);
Would the nested unset() functions interfere with the highest level foreach? In other words, are the nested $key and $value the same as the highest level $key and $value?
The solution to your problem is easier than you think it is.
Simply change the variable names for your nested loop, like so:
foreach ($data as $key => $value) {
foreach ($value as $subkey => $subvalue) {
// do stuff
}
}
With the above code, you can access the array data from $date[$key] (Which is actually equal to $value inside the parent loop) as $subkey and $subvalue respectively.
You can also still access the parent loop data anywhere inside the parent foreach loop with $key and $value respectively.
I have a key-pair array like this
$option['33']="Steak Doness";
$option['34']="Size";
$option['35']="Cooking Method";
I want to store the keys into a string like this
$key="33,34,35,";
I try to use foreach loop
$key="";
foreach($option as $key => $value) {
$key=$key.",";
}
echo $key;
However, my output is
35,
May i know which part went wrong?
You miss use the $key in your script.
The problem is with the $key which is in the foreach loop.... In each time your $key variable updated with the loop... Try with difference variable in your script.
OR, simply use
echo $key = implode(",", array_keys($option));
1st change your varible $key to $keys
replace one line
$key=$key.",";
to
$keys .= $key . ",";
it will work 100%
I've done a multistep form in PHP storing the data in a multidimensional array (I've created an array inside $_SESSION array and named it $_SESSION['inserimento'])
then i have $_SESSION['inserimento']['name'],$_SESSION['inserimento']['city']...
I would like to apply the strtolower() function to all the values before adding them to mysql
I've tried this code but it doesn't work
foreach ($_SESSION['inserimento'] as $k=>$v){
$v=strtolower($v);
}
I think I'm misunderstanding how to make a loop on multidimensional array.
Use array_map() to apply a function to all elements in an array:
$_SESSION['inserimento'] = array_map('strtolower', $_SESSION['inserimento']);
Or a regular foreach loop (inside the loop $v is a copy, so you need to affect to the original array):
foreach ($_SESSION['inserimento'] as $k => $v) {
$_SESSION['inserimento'][$k] = strtolower($v);
}
Or a foreach loop with reference ($v is no longer a copy, it is a reference to the original element):
foreach ($_SESSION['inserimento'] as &$v) {
$v = strtolower($v);
}
unset($v); // remember to unset, or $v will still be a reference to the last element after the loop
Use:
foreach ($_SESSION['inserimento'] as $k => $v) {
$_SESSION['inserimento'][$k] = strtolower($v);
}
This is happening because $v is a copy of the value inside the iteration, not a reference to the variable that contains the value.
You need to have a variable defined outside of the foreach loop.
$lowerValue = '';
foreach ($_SESSION['inserimento'] as $k => $v) {
$lowerValue = strtolower($v);
}
Try using array_walk
array_walk($_SESSION['inserimento'], function(&$value, $key) {
$value = strtolower($value);
});
The & before $value indicates that the variable is passed by reference.
I get data from an excel spreadsheet, loop over it, save it to an array. Then, I loop over that data twice.
I do:
foreach($someData as $key => $value) {
}
and I will need to foreach that same array again. Is there any way I can make it so i can use $key => $value again without causing any problems?
It sounds like you only need one loop, but to answer your question, you can just do this:
foreach($someData as $key => $value) {
#do stuff here
}
foreach($someData as $key => $value) {
#do more stuff here
}
$key and $value will get overwritten during each iteration of each loop, so there's no danger here.
Your question is a little unclear, though—if you have a foreach inside of another foreach and want to use the same set of variable names for each loop's keys and values, use a function. That's the only way to create a new local scope in PHP:
function nested_loop($arr) {
foreach($arr as $key => $value) {
#do more stuff here
}
}
foreach($someData as $key => $value) { #same names, different variables
#do stuff here
nested_loop($value);
}
So I don't think I'm making full use of the foreach loop. Here is how I understand foreach.
It goes like foreach(arrayyouwanttoloopthrough as onevalueofthatarray)
No counter or incrementing required, it automatically pulls an array, value by value each loop, and for that loop it calls the value whatever is after the "as".
Stops once it's done with the array.
Should basically replace "for", as long as dealing with an array.
So something I try to do a lot with foreach is modify the array values in the looping array. But in the end I keep finding I have to use a for loop for that type of thing.
So lets say that I have an array (thing1, thing2, thing3, thing4) and I wanted to change it....lets say to all "BLAH", with a number at the end, I'd do
$counter = 0;
foreach($array as $changeval){
$counter++;
$changeval = "BLAH".$counter;
}
I would think that would change it because $changeval should be whatever value it's at for the array, right? But it doesn't. The only way I could find to do that in a] foreach is to set a counter (like above), and use the array with the index of counter. But to do that I'd have to set the counter outside the loop, and it's not even always reliable. For that I'd think it would be better to use a for loop instead of foreach.
So why would you use foreach over for? I think I'm missing something here because foreach has GOT to be able to change values...
Thanks
OH HEY One more thing. Are variables set in loops (like i, or key) accessible outside the loop? If I have 2 foreach loops like
foreach(thing as value)
would I have to make the second one
foreach(thing2 as value2) ]
or else it would have some problems?
You can use a reference variable instead:
foreach ($array as &$value)
{
$value = "foo";
}
Now the array is full of foo (note the & before $value).
Normally, the loop variable simply contains a copy of the corresponding array element, but the & (ampersand) tells PHP to make it a reference to the actual array element, rather than just a copy; hence you can modify it.
However, as #Tadeck says below, you should be careful in this case to destroy the reference after the loop has finished, since $value will still point to the final element in the array (so it's possible to accidentally modify it). Do this with unset:
unset($value);
The other option would be to use the $key => $value syntax:
foreach ($array as $key => $value)
{
$array[$key] = "foo";
}
To answer your second question: yes, they are subsequently accessible outside the loop, which is why it's good practice to use unset when using reference loop variables as in my first example. However, there's no need to use new variable names in subsequent loops, since the old ones will just be overwritten (with no unwanted consequences).
You want to pass by reference:
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value)
{
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
The extended foreach syntax is like this:
foreach ($array as $key => $value) {
}
Using the $key, you can index the original array:
foreach ($array as $key => $value) {
$array[$key] = "BLAH";
}
Incrementing from 0 to ...
foreach($array as $changeval){
if (!isset($counter)) { $counter = 0; }
$counter++;
$changeval = "BLAH".$counter;
}
Using the index/key of the ARRAY
foreach($array as $key => $changeval){
$changeval = "BLAH".$key;
}
You can use the key when looping with foreach:
foreach ($array as $key => $value)
{
$array[$key] = "foo";
}
But note that using a reference like Will suggested will be faster for such a case - but anyway, the $key => $value-syntax is quite useful sometimes.