Liolikas Bramanovas
Liolikas Bramanovas

Reputation: 157

PHP array doubling digits

I have an array and I want to double it but after executing the array doesn't change how to correct it as minimally as possible.

<?php
   $arr = array(1, 2, 3, 4);
   foreach ($arr as $value) {
     $value = $value * 2;
   }
?>

Upvotes: 3

Views: 92

Answers (5)

num8er
num8er

Reputation: 19372

Try the following code:

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

Upvotes: 0

Girish
Girish

Reputation: 12127

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

Upvotes: 0

Aman Rawat
Aman Rawat

Reputation: 2625

You are using a variable $value which is assigning in each for loop so this value stored in $value is overwrithing in your foreach loop. You have

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

Upvotes: 0

Daan
Daan

Reputation: 12246

Your values didn't double because you're not saying the key should be overwritten in $arr this code should be working:

$arr = array(1,2,3,4);
foreach($arr as $key => $value){
  $arr[$key] = $value*2;
}

An alternative would 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);
?>

Upvotes: 2

Yasen Zhelev
Yasen Zhelev

Reputation: 4045

You need to double the actual array $arr element, not just the value in the cycle.

<?php
   $arr = array(1, 2, 3, 4);
   foreach ($arr as $key => $value) {
     $arr[$key] = $value * 2;
   }
?>

Upvotes: 0

Related Questions