PHP equals arrow operator in a foreach loop [duplicate] - php

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.

Related

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.

How can I unset a key by key name within all subarrays in an array? [duplicate]

This question already has answers here:
PHP Recursively unset array keys if match
(11 answers)
Closed 9 years ago.
Say I have an array that looks somewhat like this: array("a"=>array("a"=>"b"), "b"=>array("a"=>"d")).
I would like to unset all vars with the key "a" within the array and it sub-arrays. Assume that the data's structure is unknown. All I want is that if the key "a" exists somewhere within the parent array or it sons - it'll be unset. Is it possible?
function unsetKey (&$array, $key) {
foreach ($array as $k => $v)
if (is_array($v))
unsetKey($array[$k], $key);
if (isset($array[$key])) unset(array[$key]);
}
That should do it.

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

What does "=>" mean in PHP?

What does the => operator mean in the following code?
foreach ($user_list as $user => $pass)
The code is a comment at PHP.net.
The user does not specify the value of $user_list, $user or $pass.
I normally see that => means equal or greater than.
However, I am not sure about its purpose here because it is not assigned.
I read the code as
process a list of users in integers
such that the value of each user is equal or greater than password
The above does not make sense to me.
=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass.
Example:
$user_list = array(
'dave' => 'apassword',
'steve' => 'secr3t'
);
foreach ($user_list as $user => $pass) {
echo "{$user}'s pass is: {$pass}\n";
}
// Prints:
// "dave's pass is: apassword"
// "steve's pass is: secr3t"
Note that this can be used for numerically indexed arrays too.
Example:
$foo = array('car', 'truck', 'van', 'bike', 'rickshaw');
foreach ($foo as $i => $type) {
echo "{$i}: {$type}\n";
}
// prints:
// 0: car
// 1: truck
// 2: van
// 3: bike
// 4: rickshaw
It means assign the key to $user and the variable to $pass
When you assign an array, you do it like this
$array = array("key" => "value");
It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.
According to the PHP Manual, the '=>' created key/value pairs.
Also, Equal or Greater than is the opposite way: '>='. In PHP the greater or less than sign always goes first: '>=', '<='.
And just as a side note, excluding the second value does not work like you think it would. Instead of only giving you the key, It actually only gives you a value:
$array = array("test" => "foo");
foreach($array as $key => $value)
{
echo $key . " : " . $value; // Echoes "test : foo"
}
foreach($array as $value)
{
echo $value; // Echoes "foo"
}
Code like "a => b" means, for an associative array (some languages, like Perl, if I remember correctly, call those "hash"), that 'a' is a key, and 'b' a value.
You might want to take a look at the documentations of, at least:
foreach
arrays
Here, you are having an array, called $user_list, and you will iterate over it, getting, for each line, the key of the line in $user, and the corresponding value in $pass.
For instance, this code:
$user_list = array(
'user1' => 'password1',
'user2' => 'password2',
);
foreach ($user_list as $user => $pass)
{
var_dump("user = $user and password = $pass");
}
Will get you this output:
string 'user = user1 and password = password1' (length=37)
string 'user = user2 and password = password2' (length=37)
(I'm using var_dump to generate a nice output, that facilitates debuging; to get a normal output, you'd use echo)
"Equal or greater" is the other way arround: "greater or equals", which is written, in PHP, like this; ">="
The Same thing for most languages derived from C: C++, JAVA, PHP, ...
As a piece of advice: If you are just starting with PHP, you should definitely spend some time (maybe a couple of hours, maybe even half a day or even a whole day) going through some parts of the manual :-)
It'd help you much!
An array in PHP is a map of keys to values:
$array = array();
$array["yellow"] = 3;
$array["green"] = 4;
If you want to do something with each key-value-pair in your array, you can use the foreach control structure:
foreach ($array as $key => $value)
The $array variable is the array you will be using. The $key and $value variables will contain a key-value-pair in every iteration of the foreach loop. In this example, they will first contain "yellow" and 3, then "green" and 4.
You can use an alternative notation if you don't care about the keys:
foreach ($array as $value)
Arrays in PHP are associative arrays (otherwise known as dictionaries or hashes) by default. If you don't explicitly assign a key to a value, the interpreter will silently do that for you. So, the expression you've got up there iterates through $user_list, making the key available as $user and the value available as $pass as local variables in the body of the foreach.
$user_list is an array of data which when looped through can be split into it's name and value.
In this case it's name is $user and it's value is $pass.

Categories