Can't access original array in foreach loop - php

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

Related

PHP Looping through each item on a one dimensional array

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

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 Array storing key from a foreach loop into string

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%

Using foreach effectively in PHP

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.

How to get an array repeat in foreach loop

This is my $settings array.... and I would like to look this array in foreach so that I can read the $settings['node']['type'][$value['type']]['modifiers'] values in foreach loop and print them.
I'm can only guess you want to iterate over each element in your array.
foreach($settings as $node=>$types){
foreach($types as $values=>$modifiers){
\\ etc etc etc
echo "Settings: $node $types $values $modifiers";
}
}
Just keep nesting the foreach loops for each element you want to iterate.

Categories