0

Here when I don't use unset() function and print_r($color), it outputs YELLOW as a result. I don't get why it outputs only YELLOW?

$colors = array('red', 'blue', 'green', 'yellow');
foreach ($colors as $color)  {
    $color = strtoupper($color);
}
unset($color);
print_r($colors); // outputs: Array ( [0] => RED [1] => BLUE [2] => GREEN [3] => YELLOW )
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Akshay Kumar
  • 115
  • 1
  • 2
  • 7

3 Answers3

1

At the completion of the foreach loop, $color contains the last element Array , and then is changed to upper case ie it contains "YELLOW". If you print out it's contents using print_r it will output "YELLOW" unless you have already unset it.

What do you want to do? if you want to change each element of the array to upper case, you need to use the following foreach loop:

    foreach ($colors as &$color)  {
        $color = strtoupper($color);
    }
    print_r($colors);
Igor Carvalho
  • 668
  • 5
  • 19
0

This is because you are using $color as a variable. You should define $color as an array and store the color value in it.

<?php
$colors = array('red', 'blue', 'green', 'yellow');
 $colorArr = array();    
foreach ($colors as $color)  {
    if($color=='yellow'){
     continue;
    }
    $colorArr[] = strtoupper($color);        
}
//unset($color[3]);
echo '<pre>';
print_r($colorArr);
echo '</pre>';
?>

Note: put a condition and check if there is color in the loop then continue the loop.

if($color=='yellow'){
 continue;// continue the loop without going to assign it in array
}

Output:

Array
(
    [0] => red
    [1] => blue
    [2] => green        
)
Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
0

you unset $color and not the entry $colors[3]

if you need unset the yellow entry then

unset($colors[3]);

otherwise if want unset all the array content then

unset($colors);
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107