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;
   }
?>

      

+3


source to share


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


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;
   }
?>

      

0


source


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


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

0


source


Try using the following code:

   $arr = array(1, 2, 3, 4);
   array_walk($arr, function(&$item){ 
       $item*=2; 
   });
   var_dump($arr);

      

0


source







All Articles