$value = 1234;
$number_array = str_split($value);
for($i = 0; $i < sizeof($number_array); $i++) {
$number_array[$i] *= 10;
}
// output: 10, 20, 30, 40.
foreach($number_array as &$value) {
$value *= 10;
}
// output: 10, 20, 30, 30.
Can someone explain why the for loop gives the desired result, but the foreach doesn't?
Here is the result with var_dump
:
for($i = 0; $i < sizeof($number_array); $i++) {
$number_array[$i] *= 10;
var_dump($number_array[$i]);
}
// output: int(10) int(20) int(30) int(40)
foreach($number_array as &$value) {
$value *= 10;
var_dump($value);
}
// output: int(100) int(200) int(300) int(400)
The output is different because you assigned to each variable their multiplication by 10 in the first loop and you do it again in the second.
If you call them individually with the same values, they will do the same output.
This two loops have exactly same result if you call it separately. But in first loop you are changing $number_array. Before first loop it's value is [1,2,3,4] and after it is [10,20,30,40].
take a look:
$value = 1234;
$number_array = str_split($value);
for($i = 0; $i < sizeof($number_array); $i++) {
$number_array[$i] *= 10;
}
var_dump($number_array); // 10, 20, 30, 40
foreach($number_array as &$value) {
$value *= 10;
}
P.S if you want to get same result for each loop, change your code like that:
$value = 1234;
$number_array = str_split($value);
for($i = 0; $i < sizeof($number_array); $i++) {
$x = $number_array[$i];
$x *= 10;
echo $x."</br>";
}
echo "---</br>";
foreach($number_array as &$value) {
$value *= 10;
echo $value."</br>";
}
Note: don't change values into array, but write them in $x
variable and change it
Because for loop changes the values of $number_array
do like this will give same result
$value = 1234;
$number_array = str_split($value);
foreach($number_array as $value) {
$value *= 10;
echo $value;
// output: 10, 20, 30, 40.
}
for($i = 0; $i < sizeof($number_array); $i++) {
$number_array[$i] *= 10;
}
// output: 10, 20, 30, 40.
print_r($number_array);
It turned out the loop I was using to create the string was causing the incorrect output because I used $value
again in the foreach loop of the string.
$value = 1234;
$number_array = str_split($value);
foreach($number_array as &$value) {
$value *= 10;
}
foreach($number as $value) {
$answr .= $value . " ";
}
// $answr = 10 20 30 30
Once I had changed the loop to $num
to test, the correct output was printed.
foreach($number as $num) {
$answr .= $num . " ";
} //$answr: 10 20 30 40
An unsual quirk, that I haven't quite got my head around yet, but I'm assuming it's because $value
was still set as a var during the second foreach loop.
Thank you for all answers and I apologise for not posting the whole code snippet and causing confusion.