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.
Related
This question already has answers here:
PHP Remove elements from associative array
(9 answers)
Closed 5 years ago.
The title says it all. I want to delete the highlighted section in yellow as shown in picture below. And rest remain unchanged. What is the best way to do it? Is there a method that does't use foreach?
you can do this just with one foreach!
foreach ($data as $key => $subArr) {
unset($subArr['id']);
$data[$key] = $subArr;
}
You can use the following
$filteredArray = array_map(function($array) {
unset($array['id']);
return $array;
}, $dataArray);
Instead of doing foreach() loop on the array, You can go with array_search()
$results=array_search($unwantedValue,$array,true);
if($results !== false) {
unset($array[$result]);
}
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.
This question already has answers here:
Array as session variable
(4 answers)
Closed 9 years ago.
I was wondering is it possible to have an associative array within a session array? If so, what would be the best way to do it and how can I loop through it? I have tried the following but it doesnt seem to work:
//The variables are post variables from a form
$_SESSION['users'][$id] = array('name'=>$name, 'status'=>$status, 'salary'=>"20000");
Here is how I am trying to loop through the session array:
foreach ($_SESSION['users'] as $id=>$value) {
echo $value;
}
Also, If I knew an id how can I get the name? Can I do $_SESSION['users']['1234']['name']?
Yes you can have an associative array within a session array. You can also loop through it with a for or a foreach loop. e.g.:
$array = $_SESSION['users'][$id];
foreach($array as $key => $value) {
var_dump($array[$key]); //Will dump info about a single element
}
However, it would be helpful to see your error message or additional details of what you are trying to do and what about it that isn't working.
EDIT
Based on your updated question, since you are accessing and array of arrays (theoretically) you would need to nest a foreach with another foreach to get at your values.
foreach($_SESSION['users'] as $arrays) {
foreach($arrays as $arrKey => $arrVal) {
var_dump($arrays[$arrKey]);
}
}
Running that on your data would output (with my own fake data to fill variables):
string(7) "johndoe"
string(6) "active"
string(5) "20000"
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);
}
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