PHP array doubling digits
5 answers
Your values didn't double because you don't say the key should be overwritten in $arr
, this code should work:
$arr = array(1,2,3,4);
foreach($arr as $key => $value){
$arr[$key] = $value*2;
}
An alternative could be to use array_map()
.
<?php
function double($i){
return $i*2;
}
$arr = array(1, 2, 3, 4);
$arr = array_map('double', $arr);
var_dump($arr);
?>
+2
source to share
You are using the $ value variable that is assigned in each for loop, so this value stored in the $ value is overwritten in your foreach loop. You
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
$value = $value * 2;
}
?>
This will work
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
print_r($arr);
?>
0
source to share