Take a look to this code, and help me to understand the result
$x = array('hello', 'beautiful', 'world');
$y = array('bye bye','world', 'harsh');
foreach ($x as $n => &$v) { }
$v = "DONT CHANGE!";
foreach ($y as $n => $v){ }
print_r($x);
die;
It prints:
Array
(
[0] => hello
[1] => beautiful
[2] => harsh
)
Why it changes the LAST element of the $x? it just dont follow any logic!
After this loop is executed:
foreach ($x as $n => &$v) { }
$v ends up as a reference to $x[2]. Whatever you assign to $v actually gets assigned $x[2]. So at each iteration of the second loop:
foreach ($y as $n => $v) { }
$v (or should I say $x[2]) becomes:
'bye bye'
'world'
'harsh'
// ...
$v = "DONT CHANGE!";
unset($v);
// ...
because $v is still a reference, which later takes the last item in the last foreach loop.
EDIT: See the reference where it reads (in a code block)
unset($value); // break the reference with the last element
Foreach loops are not functions.An ampersand(&) at foreach does not work to preserve the values like at functions.
So even if you have $var in the second foreach () do not expect it to be like a "ghost" out of the loop.
Related
I have some array to go through foreach. Inside, I need to generate an array of quantity.
It still brings me back in both 0-5.
The output should look like this:
$a = array(['id' => 1,'quantity' => 5,'input' => 'one'],
['id' => 2,'quantity' => 4,'input' => 'two'] );
foreach ($a as $b) {
for ($x = 0; $x <= $b['quantity']; $x++) {
$count[$x] = $x;
}
dump($b['quantity']);
dump($count);
}
Well it's hard to tell what you want to achieve, but I think your current described problem is, that you are overwriting the same array in your second loop and so it still contains 5 elements from the first loop.
Add this at the top of your foreach:
foreach ($a as $b) {
$count = [];
...
This will reset the $count array on every iteration. This might bring new problems, but that's not easy to tell by the supplied information..
I'm trying to increment the value for $variable each time a duplicate variable occurs. I'm not sure if this is syntactically correct, but I think this is semantically correct. var_dump seems to spit out the correct outputs, but i get this error: Notice: Undefined index...
$newarray = array();
foreach ($array as $variable)
{
$newarray[$variable]++;
var_dump($newarray);
}
$array = (0 => h, 1 => e, 2 => l, 3=> l, 4=> o);
goal:
'h' => int 1
'e' => int 1
'l' => int 2
'o' => int 1
My code works, it's just that I get some weird NOTICE.
$newarray = array();
foreach ($array as $variable)
{
if (!isset($newarray[$variable])) {
$newarray[$variable] = 0;
}
$newarray[$variable]++;
}
Take a look at the function array_count_values(). It does exactly what you are trying to do.
Sample from php.net:
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
Result:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
In modern PHP, you can avoid the isset() call by leveraging the null coalescing operator. In the snippet below, the technique sets the variable to 0 if the variable is not yet declared. Then you can freely use a range of shorthand manipulations such as concatenation, arithmetic, etc.
$new = [];
foreach ($array as $v) {
$new[$v] = ($new[$v] ?? 0) + 1;
}
Or if you want to continue using ++, then you can use the "null coalescing assignment operator". The logic on the right side of assignment is not even executed if the variable is already declared. The below snippet will perform identically to the above snippet.
$new = [];
foreach ($array as $v) {
$new[$v] ??= 0;
++$new[$v];
}
<?php
$newarray = array();
foreach ($array as $variable) {
if ( !array_key_exists($variable, $newarray) ) {
$newarray[$variable] = 0;
}
++$newarray[$variable];
}
var_dump($newarray);
But you could also use array_count_values() instead.
$newarray = array();
foreach ($array as $variable)
{
if(!isset($newarray[$variable]))
$newarray[$variable] = 0;
$newarray[$variable]++;
var_dump($newarray);
}
You are incrementing the wrong thing, try this instead:
foreach ($array as $key => $variable) {
$array[$key]++;
var_dump($array);
}
I have an array_flipped array that looks something like:
{ "a" => 0, "b" => 1, "c" => 2 }
Is there a standard function that I can use so it looks like (where all the values are set to 0?):
{ "a" => 0, "b" => 0, "c" => 0 }
I tried using a foreach loop, but if I remember correctly from other programming languages, you shouldn't be able to change the value of an array via a foreach loop.
foreach( $poll_options as $k => $v )
$v = 0; // doesn't seem to work...
tl; dr: how can I set all the values of an array to 0? Is there a standard function to do this?
$array = array_fill_keys(array_keys($array), 0);
or
array_walk($array, create_function('&$a', '$a = 0;'));
You can use a foreach to reset the values;
foreach($poll_options as $k => $v) {
$poll_options[$k] = 0;
}
array_fill_keys function is easiest one for me to clear the array. Just use like
array_fill_keys(array_keys($array), "")
or
array_fill_keys(array_keys($array), whatever you want to do)
foreach may cause to decrease your performance to be sure that which one is your actual need.
Run your loop like this, it will work:
foreach( $poll_options as $k => $v )
$poll_options[$k] = 0;
Moreover, ideally you should not be able to change the structure of the array while using foreach, but changing the values does no harm.
As of PHP 5.3 you can use lambda functions, so here's a functional solution:
$array = array_map(function($v){ return 0; }, $array);
You have to use an ampersand...
foreach( $poll_options as &$v)
$v = 0;
Or just use a for loop.
you can try this
foreach( $poll_options as $k => &$v )
$v = 0;
Address of $v
array_combine(array_keys($array), array_fill(0, count($array), 0))
Would be the least manual way of doing it.
There are two types for variable assignment in PHP,
Copy
Reference
In reference assignment, ( $a = &$b ), $a and $b both, refers to the same content. ( read manual )
So, if you want to change the array in thesame time as you doing foreach on it, there are two ways :
1- Making a copy of array :
foreach($array as $key=>$value){
$array[$key] = 0 ; // reassign the array's value
}
2 - By reference:
foreach($array as $key => &$value){
$value = 0 ;
}
So here is my code:
<?php
$arr = array(array(2 => 5),
array(3 => 4),
array(7 => 10));
foreach ($arr as $v) {
$k = key($v);
if ($k > 5) {
// unset this element from $arr array
}
}
print_r($arr);
// now I would like to get the array without array(7 => 10) member
As you can see, I start with an array of single key => value arrays, I loop through this array and get a key of the current element (which is a single item array).
I need to unset elements of the array with key higher than 5, how could I do that? I might also need to remove elements with value less than 50 or any other condition. Basically I need to be able to get a key of the current array item which is itself an array with a single item.
foreach($arr as $k => $v) {
if(key($v) > 5) {
unset($arr[$k]);
}
}
It is safe in PHP to remove elements from an array while iterating over it using foreach loop:
foreach ($arr as $key => $value) {
if (key($value) > 5) {
unset($arr[$key]);
}
}
Use key() to get the first key from the sub-array.
foreach($arr as $k => $v) {
if(key($v) > 5) {
unset($arr[$k]);
}
}
It's not really safe to add or delete from a collection while iterating through it. How about adding the elements you want to a second array, then dumping the original?
To unset array element we Used unset() and php function like below:
foreach($array as $key=>$value)
{
if(key($value) > 5)
{
unset($array[$key]);
}
}
How can I do the following without lots of complicated code?
Explode each value of an array in PHP (I sort of know how to do this step)
Discard the first part
Keep the original key for the second part (I know there will be only two parts)
By this, I mean the following:
$array[1]=blue,green
$array[2]=yellow,red
becomes
$array[1]=green //it exploded [1] into blue and green and discarded blue
$array[2]=red // it exploded [2] into yellow and red and discarded yellow
I just realized, could I do this with a for...each loop? If so, just reply yes. I can code it once I know where to start.
given this:
$array[1] = "blue,green";
$array[2] = "yellow,red";
Here's how to do it:
foreach ($array as $key => $value) {
$temp = explode(",", $value, 2); // makes sure there's only 2 parts
$array[$key] = $temp[1];
}
Another way you could do it would be like this:
foreach ($array as $key => $value) {
$array[$key] = preg_replace("/^.+?,$/", "", $value);
}
... or use a combination of substr() and strpos()
Try this:
$arr = explode(',','a,b,c');
unset($arr[0]);
Although, really, what you're asking doesn't make sense. If you know there are two parts, you probably want something closer to this:
list(,$what_i_want) = explode('|','A|B',2);
foreach ($array as $k => &$v) {
$v = (array) explode(',', $v);
$v = (!empty($v[1])) ? $v[1] : $v[0];
}
The array you start with:
$array[1] = "blue,green";
$array[2] = "yellow,red";
One way of coding it:
function reduction($values)
{
// Assumes the last part is what you want (regardless of how many you have.)
return array_pop(explode(",", $values));
}
$prime = array_map('reduction', $array);
Note: This creates a different array than $array.
Therefore $array == $prime but is not $array === $prime