For each array modification [duplicate] - php

This question already has answers here:
Why can't I update data in an array with foreach loop? [duplicate]
(3 answers)
Closed 8 years ago.
I have this following code:
foreach ($animals as $animal) {
$animal = getOffSpring($animal);
}
Since I am setting $animal to a new string, will I be modifying the array as well please?
My run suggests that my array remains the same, but I want it to be modified with the new value. Is this the bug?
In other words, I want all the animals within my array to be modified to their offsprings

I think you are trying to do that.
When you take $animal variable and pass it to a function or modifie it inside foreach loop, you work with independent variable, that isn't linked to $animals array in any way ( if you don't link it yourself ), therefore all changes applied to it, don't result in modification of $animals array.
foreach ( $animals as $i => $animal )
{
$animals[ $i ] = getOffSpring( $animal );
}
As #AlecTMH mentioned in his comment, array_map is also a solution.
array_map( 'getOffSpring', $animals );

You can use a reference:
foreach ($animals as &$animal) {
$animal = getOffSpring($animal);
}
unset($animal);
The unset after the loop clears the reference. Otherwise you keep a reference to the last array element in $animal after the loop which will cause annoying problems if you forget about this and then use $animal later for something else.
Another option would be using the key to replace it:
foreach ($animals as $key => $animal) {
$animals[$key] = getOffSpring($animal);
}

You can use a reference to the value in the array
foreach ($animals as &$animal) {
$animal = getOffSpring($animal);
}

Related

Using PHP foreach How to get first item from DB then others [duplicate]

This question already has answers here:
PHP - Grab the first element using a foreach
(10 answers)
Closed 5 years ago.
how can I get first item from db by foreach
$posts = new Posts();
$post = $posts->feature_post($conn);
foreach($post as $feature) { ?>
my html code is different for 1st item. so I need to get 1st item then other item,
how I can do it?
thanks in advance.
To get the first item of an array, you can use the reset function
http://php.net/manual/fr/function.reset.php
<?php
$posts = new Posts();
$listPost = $posts->feature_post($conn);
$firstPost = reset($listPost);
...
Also if you want to know if you loop through the first element and if the keys of your arrays are 0,1,2,3 etc..
<?php
foreach($array as $key => $cell) {
if ($key === 0) {
// this is your first element
....
}
}
If the keys of your array are not numeric indexes but you don't intend to use them, you can obtain such array by using the array_values function

PHP - Unsetting array element in a foreach loop [duplicate]

This question already has answers here:
How do you remove an array element in a foreach loop?
(6 answers)
Closed 6 years ago.
Hi I am trying to remove an array element using a foreach loop, but it does nothing. I need the index to be completely gone rather than making it null. Here is what I have tried:
foreach ($_SESSION['cart'] as &$arrays3) {
if($arrays3['id'] == $id){
unset($arrays3);
}
}
Note, the array value for each key contains an associative array.
You need to use the key from your foreach, and unset the variable directly (from the session):
foreach ($_SESSION['cart'] as $key => $arrays3) {
if($arrays3['id'] == $id){
unset($_SESSION['cart'][$key]);
}
}
Unsetting $arrays3 or any of its children will only be effective until the next iteration of the foreach loop, when it will be set again.
You are using a dangerous form of the foreach loop. You MUST always unset the reference variable after the loop:
foreach ($_SESSION['cart'] as &$arrays3) {}
unset($arrays3);
Otherwise things will break if that loop is used again.
And the reference really is not needed. foreach operates on a copy of the array, so changes to the key or value will not go back into the original array, but you can always access the original array, as shown in the answer of #scrowler.

PHP - Ampersand before the variable in foreach loop [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Reference - What does this symbol mean in PHP?
I need to know why we use ampersand before the variable in foreach loop
foreach ($wishdets as $wishes => &$wishesarray) {
foreach ($wishesarray as $categories => &$categoriesarray) {
}
}
This example will show you the difference
$array = array(1, 2);
foreach ($array as $value) {
$value++;
}
print_r($array); // 1, 2 because we iterated over copy of value
foreach ($array as &$value) {
$value++;
}
print_r($array); // 2, 3 because we iterated over references to actual values of array
Check out the PHP docs for this here: http://pl.php.net/manual/en/control-structures.foreach.php
This means it is passed by reference instead of value... IE any manipulation of the variable will affect the original. This differs to value where any modifications don't affect the original object.
This is asked many times on stackoverflow.
It is used to apply changes in single instance of array to main array..
As:
//Now the changes wont affect array $wishesarray
foreach ($wishesarray as $id => $categoriy) {
$categoriy++;
}
print_r($wishesarray); //It'll same as before..
But Now changes will reflect in array $wishesarray also
foreach ($wishesarray as $id => &$categoriy) {
$categoriy++;
}
print_r($wishesarray); //It'll have values all increased by one..
For the code in your question, there can be no specific answer given because the inner foreach loop is empty.
What I see with your code is, that the inner foreach iterates over a reference instead of the common way.
I suggest you take a read of the foreach PHP Manual page, it covers all four cases:
foreach($standard as $each);
foreach($standard as &$each); # this is used in your question
$reference = &$standard;
foreach($reference as $each);
$reference = &$standard;
foreach($reference as &$each); # this is used in your question

PHP: replace array value doesn't stay after foreach loop

I'm changing the value in a multi-dimensional array and it's not staying outside of the foreach loop that's being used to traverse it.
My array initially looks something like this:
Array
{
[0] => Array
{
[name] => Bob
[age] => 33
[state] => CA
[visited] => 0
}
...
}
My PHP gets into it by going:
foreach ($people as $person){
echo $person['name']
....
logic for the visited variable
...
$person['visited'] = $calculated_visit_value;
}
If I
print_r($person)
at the end (but inside) of the foreach loop everything looks good, the value for visited is set. However, if I print_r($people) outside of the loop, $person['visited'] is not set. I don't know what I'm doing wrong.
Help is appreciated.
You are creating a new variable called $person from within that for loop and your array will never see the scope of that new variable.
You can try passing it by reference, like so:
foreach ($people as &$person){
echo $person['name'];
....
logic for the visited variable
...
$person['visited'] = $calculated_visit_value;
}
From foreach's documentation:
Unless the array is referenced, foreach operates on a copy of the
specified array and not the array itself. foreach has some side
effects on the array pointer. Don't rely on the array pointer during
or after the foreach without resetting it.
What this means is that your $person variable is a copy of what was in the array, similar in effect to this code (note that this code is for understanding only and wrong on many levels, in reality you would use the reset(), current() and next() function to loop properly over your array, see here):
for ($i = 0; $i < count($people); $i++) {
$person = $people[$i];
// code inside your foreach ...
}
So if you change the content of $person, you don't actually modify what's inside the $people array
To solve that, you can either use a referenced foreach:
foreach ($people as &$person) { // note the &
$person = $calculated_visit_value; // $person is now a reference to the original value inside $people and thus this will work as intended
}
Note that the refence is not cleared when the foreach loop ends, so at the end of it $person is still a reference to the last element of $people.
If you don't know what references are, please refer to the documentation for more info.
Or use the key to access the original array:
foreach ($people as $person_index => $person) {
$people[$person_index] = $calculated_visit_value;
}
For your information, you can use the two together
foreach ($people as $person_index => &$person { ...
The $person array is generated on each iteration, so setting that value would be overwritten on the next go through anyway.
But even so, that array only exists during the loop. You should create another array before the loop and put your values into that array during the loop.
As it has been told, "you are creating a new variable called $person from within that for loop and your array will never see the scope of that new variable."
I find this solution more robust :
foreach ($people as $key => $person)
{
echo $person['name'];
//logic for the visited variable
$people[$key]['visited']=$calculated_visit_value;
}

Unset an array element inside a foreach loop [duplicate]

This question already has answers here:
How do you remove an array element in a foreach loop?
(6 answers)
Closed 6 years ago.
I'm accessing an array by reference inside a foreach loop, but the unset() function doesn't seem to be working:
foreach ( $this->result['list'] as &$row ) {
if ($this_row_is_boring) {
unset($row);
}
}
print_r($this->result['list']); // Includes rows I thought I unset
Ideas? Thanks!
You're unsetting the reference (breaking the reference). You'd need to unset based on a key:
foreach ($this->result['list'] as $key => &$row) {
if ($this_row_is_boring) {
unset($this->result['list'][$key]);
}
}
foreach ($this->result['list'] as $key => &$row) {
if ($this_row_is_boring) {
unset($this->result['list'][$key]);
}
}
unset($row);
Remember: if you are using a foreach with a reference, you should use unset to dereference so that foreach doesn't copy the next one on top of it. More info
A bit of an explanation to the answers above.
After unset($row) the variable $row is unset. That does not mean the data in $row is removed; the list also has an element pointing to $row.
It helps to think of variables as labels. A piece of data can have one or more labels, and unset removes that label but does not touch the actual data. If all labels are removed the data is automatically deleted.

Categories