I'm practicing on foreach and for loop at the moment and combining them leads me to unexpected result. Below is a foreach statement inside the for loop statement.
PHP:
<?php
$names = array("A", "B", "C", "D");
for ($i = 0; $i <= 3; $i++)
{
foreach ($names as $name)
{
echo "$name = $i ";
}
}
?>
OUTPUT:
A = 0 B = 0 C = 0 D = 0 A = 1 B = 1 C = 1 D = 1 A = 2 B = 2 C = 2 D = 2 A = 3 B = 3 C = 3 D = 3
EXPECTED OUTPUT:
A = 0 B = 1 C= 2 D = 3
Kindly tell me what I'm doing wrong and what is the solution for this.
PS: I don't want to used array keys and values. :)
You want
foreach
only:You don't need to nest loop styles just to get the array keys - PHP can trivially give them to you with the
as $key => $value
version of foreach.