只显示数组中的最后一项 [英] Foreach only showing last item in array
问题描述
$ message ==kk,ll;
$ myArray = explode(',',$ message);
print_r($ myArray);
foreach($ myArray as $ value);
{
echo$ value< br>;
$ array [] = $ value;
}
print_r($ array);
输出结果为:
Array([0] => kk [1] => ll)ll
Array([0] => ll)
您可以看到当我使用 print_r()
时,数组包含两个项目。但是 foreach
循环只能循环使用最后一项。将数组元素添加到循环中的新数组中也最终得到一个只包含最后一个元素的数组。我在做什么错了?
在你的代码中有两个错误:
-
在第一行中,有两个等号,应该只有一个。
在您的foreach循环,你错误地把分号放在最后: In your first line you have two equal signs which should only be one.
In your foreach loop, you have by mistake put an semicolon at the end:
$ b $
foreach($ myArray as $ value);
这样做,foreach循环将运行,但是 代码应该如下所示: 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. The output is: You can see that when I use You have two mistakes in you code: Doing this, the foreach loop will run, but the code inside the The code should look like this:
这篇关于只显示数组中的最后一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! {} / code>实际上放置在foreach循环之外,从而导致
$ value
只存储数组的最后一个元素。
$ message =kk ,二;
$ myArray = explode(',',$ message);
print_r($ myArray);
foreach($ myArray as $ value){
echo$ value< br>;
$ array [] = $ value;
}
print_r($ array);
$message == "kk,ll";
$myArray = explode(',', $message);
print_r ($myArray);
foreach ($myArray as $value);
{
echo "$value <br>";
$array[] = $value;
}
print_r ($array);
Array ( [0] => kk [1] => ll ) ll
Array ( [0] => ll )
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?
foreach ($myArray as $value);
{}
is actually placed outside the foreach loop, and thereby causing $value
only to store the last element of the array.$message = "kk,ll";
$myArray = explode(',', $message);
print_r ($myArray);
foreach ($myArray as $value) {
echo "$value <br>";
$array[] = $value;
}
print_r ($array);