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

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

Related

Laravel, how to delete key and value in an array of a specific position? [duplicate]

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

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.

For each array modification [duplicate]

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

PHP equals arrow operator in a foreach loop [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does $k => $v in foreach($ex as $k=>$v) mean?
I am trying to understand what this means:
foreach($this->domains as $domain=>$users) {
// some code...
}
I understand $this->domains is an array that foreach will index over. But what does as $domain=>$users mean? I have only seen the => operator used in an array to set (key, value) pairs. The class has a member called $domain, but I assume that would be accessed as $this->domain.
The => operator specifies an association. So assuming $this->domains is an array, $domain will be the key, and $users will be the value.
<?php
$domains['example.com'] = 'user1';
$domains['fred.com'] = 'user2';
foreach ($domains as $domain => $user) {
echo '$domain, $user\n';
}
Outputs:
example.com, user1
fred.com, user2
(In your example, $users is probably an array of users);
Think of it this way:
foreach($this->domains as $key=>$value) {
It will step through each element in the associative array returned by $this->domains as a key/value pair. The key will be in $domain and the value in $users.
To help you understand, you might put this line in your foreach loop:
echo $domain, " => ", $users;
Read foreach
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
The first form loops over the array given by array_expression. On each
loop, the value of the current element is assigned to $value and the
internal array pointer is advanced by one (so on the next loop, you'll
be looking at the next element).
The second form does the same thing, except that the current element's
key will be assigned to the variable $key on each loop.
$domain here is a local variable that contains the key of the current item in the array. That is if your array is:
$ages = array("dad" => 31, "mom" => 35, "son" => 2);
Then
foreach($ages as $name=>$age)
{
// prints dad is 32 years old, mom is 35 years old, etc
echo "$name is $age years old"
}
In the loop body, referring to $name would refer to the current key, ie "dad", "mom" or "son". And $age would refer to the age we've stored above at the current key.
assume that would be accessed as $this->domain.
You're right, just $domain is the local variable here. You need $this->domain to get the member variable.

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