PHP array doubling digits
I have an array and I want to double it, but after executing the array, it doesn't change how to fix it as minimal as possible.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
$value = $value * 2;
}
?>
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);
?>
You need to double the actual array $arr
, not just the value in the loop.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $key => $value) {
$arr[$key] = $value * 2;
}
?>
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);
?>
short solution and supported in < PHP 5.3
, try this code
<?php
$arr = array(1, 2, 3, 4);
$arr = array_map(create_function('$v', 'return $v * 2;'), $arr);
print_r($arr);
DEMO
Try using the following code:
$arr = array(1, 2, 3, 4);
array_walk($arr, function(&$item){
$item*=2;
});
var_dump($arr);