I want to know the construction of a loop for a loop relative to arrays
How to reindex this array after dumping the array:
echo "before deleting:<br>";
$countries[] = "Japan";
$countries[] = "Korea";
$countries[] = "china";
echo $a = count($countries);
echo "<br>";
for($i= 0;$i < $a; $i++)
{
echo "$countries[$i]<br>";
}
unset($countries[1]);
echo "<br>";
After canceling the function, the score shows 2, but the second country name china is not reflected in the loop below.
echo "<hr>After deleting:<br>";
echo $a = count($countries);
echo "<br>";
//below is my forloop
for($i=0;$i < $a; $i++)
{
echo "$countries[$i]<br>";
}
</code>
+3
source to share
2 answers
Instead
for($i=0;$i < $a; $i++)
{
echo "$countries[$i]<br>";
}
Using
foreach ($countries as $country) {
echo $country . '<br>';
}
Foreach doesn't really care about the keys of the array, so it will go through fine. If you really want to use a standard loop for
, call this before: $countries = array_values($countries);
and it will effectively reset the array keys.
+2
source to share