Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach only showing last item in array

I'm attempting to make a foreach loop to iterate over each item in an array, but it only captures the last item and does not iterate over the first one. I've stripped down the code to only show the relevant parts and added some commands to identify the problem as described above.

$message == "kk,ll";
$myArray = explode(',', $message);

print_r ($myArray);

foreach ($myArray as $value);
{   
    echo "$value <br>";
    $array[] = $value;
}

print_r ($array);

The output is:

Array ( [0] => kk [1] => ll ) ll 
Array ( [0] => ll )

You can see that when I use print_r() the array contains two items. But the foreach loop only loops over the last item. Adding the array elements into a new array inside the loop also ends up with an array containing only the last element. What am I doing wrong?

like image 690
Corey Hart Avatar asked Jan 05 '23 16:01

Corey Hart


2 Answers

You have two mistakes in you code:

  1. In your first line you have two equal signs which should only be one.

  2. In your foreach loop, you have by mistake put an semicolon at the end:

foreach ($myArray as $value);

Doing this, the foreach loop will run, but the code inside the {} is actually placed outside the foreach loop, and thereby causing $value only to store the last element of the array.

The code should look like this:

$message = "kk,ll";
$myArray = explode(',', $message);
print_r ($myArray);
foreach ($myArray as $value) {   
    echo "$value <br>";
    $array[] = $value;
}
print_r ($array);
like image 182
TheYaXxE Avatar answered Jan 08 '23 07:01

TheYaXxE


your foreach just assigned the $value, but output nothing. This is caused by the ; after foreach, same as

foreach ($myArray as $value)
{}

And after this, the $value have the last element of $myArray, then

{   
    echo "$value <br>";
    $array[] = $value;
}

only output the last element.

like image 27
LF00 Avatar answered Jan 08 '23 07:01

LF00