How can I implement scoped foreach in PHP? - php

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);
}

Related

php foreach as change variable names

Can I change the variable names used in foreach in PHP?
foreach ($sql2htmlLists as $kkkkk => $vvvvv){
instead of the default:
foreach ($sql2htmlLists as $key => $value){
Thank you
Yes, you can use whatever you want
foreach ($sql2htmlLists as $key => $value){
}
But i suggest you to use proper variables.And try to unset that variables at the end of loop to get out from conflicts.

Should I unset both `$key` and `$value` after every foreach statement?

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.

php update values of an array based on other array with the same key

I have the following scenario:
$starterArray = array ('192.168.3.41:8013'=>0,'192.168.3.41:8023'=>0,'192.168.3.41:8033'=>0);
In the requirement I have another array which counts some events of the application, this array uses the same keys as my first array, but values can change), so at the end I could have something like:
$processArray = array ('192.168.3.41:8013'=>3,'192.168.3.41:8023'=>5,'192.168.3.41:8033'=>7);
I want to update the values of my starter array with the values of the process array, for instance, at the end, I should have:
$starterArray = array ('192.168.3.41:8013'=>3,'192.168.3.41:8023'=>5,'192.168.3.41:8033'=>7);
I know this can be achieved by using $starterArray = $processArray;
Then in some moments, I would need to sum some units to the values of my array, for example +1 or +2:
It should be something like the following?
foreach ($starterArray as $key => $value) {
$starterArray[$value] = $starterArray[$value]+1;
}
Then, for my process array, I need to set the values to 0
foreach ($processArray as $key => $value) {
$processArray[$value] = 0;
}
This is what I tried but it is not working, if somebody could help me I will really appreaciate it. Thanks in advance.
PD: I know these are strange requirements, but that's what I am asked to do...
You are almost there:-
foreach ($processArray as $key => $value) {
$starterArray[$key] = $value +1;
}
and then:-
foreach ($processArray as $key => $value) {
$processArray[$key] = 0;
}
However, you could do this all in one loop:-
foreach ($processArray as $key => $value) {
$starterArray[$key] = $value +1;
$processArray[$key] = 0;
}
You need to put $key in brackets, not $value.
Or, you can do:
foreach ($starterArray as $key => &$value) {
$value++; /* put here whatever formula you want */
}
foreach ($starterArray as $key => $value) {
$starterArray[$key] = $value+1;
// or $starterArray[$key] = 0;
}

PHP Iterating Through Associative Array

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.

Simplify looping through an array which could be flat or multidimensional

Often, I will have an array holding a set of values each of which I need to process. Sometimes, the array will only hold a single set, in which case each value needs to be put through the process. Other times, the array will hold many sets, in which case each value will be an array and each value of those arrays will need to be processed. Here is an example:
foreach($array as $key => $value) {
if(is_array($value)) {
foreach($value as $subkey => $subvalue) {
//Process $subvalue here
}
}
else {
//Process $value here
}
}
The problem is that the code for processing $value/$subvalue is identical except that it operates on a different variable. One way to simplify this would be to put that code into a function but it still seems inelegant to have to call it twice. Furthermore, that would leave quite a lot of code (the foreach loops and array test) outside of that function. For example, say the process is validation, I don't want to have to write two foreach loops and an array test whenever I want to call my validation function.
Is there a simpler way of doing this?
You can use a RecursiveArrayIterator to iterate over the values in the array, e.g.
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($yourArray),
RecursiveIteratorIterator:SELF_FIRST);
Then just foreach over it. Further reading:
http://www.phpro.org/tutorials/Introduction-to-SPL.html#7
Wrap the single value into an array, then proceed as usual:
foreach($array as $key => $value) {
if(!is_array($value)) $value = array($value);
foreach($value as $subkey => $subvalue) {
//Process $value/$subvalue here
}
}
Alternatively you can create a function that handles the processing of single items, then call that same function from each branch. You'll still end up saving writing the process twice.

Categories