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.
Related
If I have array like this myarray[0]['field1','field2','field3'];
I know its basically one row and has nothing to loop through, but i need it to loop through the values rather than the whole array. In this case it would need to loop 3x but if there were 10 fields, it should loop 10x.
I've been doing this but it feels too complicated for something so simple. Is there a function that is eluding me on google for this?
foreach (myarray[0][field1] as $item){
//do something
}
foreach (myarray[0][field2] as $item){
//do something
}
foreach (myarray[0][field3] as $item){
//do something
}
Use nested loops:
foreach ($myarray[0] as $field => $field_array){
foreach ($myarray[0][$field] as $item) {
//do something
}
}
You have a 2-dimensional array, but you want to only consider the second dimension? So treat the first dimension as a variable:
foreach ($myarray[0] as $item){
echo $item;
}
If you want to know the field name and value, then:
foreach ($myarray[0] as $key=>$value){
echo $key . ' = ' . $value;
}
foreach ($myarray[0] as $field => $field_array){
foreach ($field_array as $item) {
//do something
}
}
I have a problem with my foreach loop. My foreach loop basically looks like this:
echo $values[0];
echo $values[1];
foreach ($values as $key => $value)
{
echo $values[0];
echo $values[1];
}
$values[0] should be "new york city" and $values[1] should be "new york". The problem is that in the foreach loop, both echos give the same value, whereas outside the loop they give the different (correct) values.
How do I access the original array ($values) normally inside of the foreach loop?
EDIT: I don't want to access the value $value. I want to be able to access any index of $values regardless of which iteration my foreach loop is on. I hope I am making sense.
Also, obviously I have alot more going on in this foreach loop, it was just meant as an example. The purpose of the foreach loop is not to print out these values.
Basically what the actual foreach loop I am using does is that it iterate through an array, and when it finds a certain value in that array, it iterates through the whole array again (inside the foreach loop). So basically I want a foreach loop inside a foreach loop, both for the same array, but it doesn't seem to work.
Try to use $val instead of $values[$i];
// Code goes here
foreach ($values as $key => $value)
{
echo $value;
}
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 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.