0

I have a php array:
Array ( [1] => 4 [2] => 3 )

I want to +2 to all the elements of the array. So the final result will be:
Array ( [1] => 6 [2] => 5 )

What is the shortest way with which I can achieve this?

I can iterate over the array through the loop and perform addition. But I was wondering if there is another way to achieve it.

  • When you say *shortest way*, in what sense do you mean, the least code, the quickest, the most obscure? – Nigel Ren Oct 08 '20 at 10:39
  • I meant the least code that would take lesser time to execute. – Pooja Shingala Oct 08 '20 at 10:41
  • This might be of some help https://stackoverflow.com/a/15549249/11656450 – Moshe Gross Oct 08 '20 at 10:42
  • 2
    Does this answer your question? [Performance of foreach, array\_map with lambda and array\_map with static function](https://stackoverflow.com/questions/18144782/performance-of-foreach-array-map-with-lambda-and-array-map-with-static-function) – Nico Haase Oct 08 '20 at 10:42
  • If you ask in terms of speed, `foreach` will be slightly faster than `array_map`. Link given by Nico Hasse gives a good explanation of the same with benchmarks. – Manish Pareek Oct 08 '20 at 10:55
  • 2
    I still find it interesting that all of the answers are still longer (and probably slower) than `foreach ( $array as &$v) $v+=2;` (although I wouldn't normally miss out the `{}`'s), but shows how little code this really needs. – Nigel Ren Oct 08 '20 at 10:57

3 Answers3

2

did you try:

$newArray = array_map(function ($value) {
   return $value + 2;
}, $myArray);
Sami Akkawi
  • 193
  • 3
  • 9
1

You can use array_walk to do that.

$array = [1, 2, 3, 4];
array_walk($array, function(&$item) { $item += 2; });
var_dump($array);
Chonchol Mahmud
  • 2,717
  • 7
  • 39
  • 72
0

Try this code it's work properly.

onedimensional array time use below code

<?php
    echo "<pre>";        
    // onedimensional array time use below code
    $a = [4,3];
    echo "<br>A Input : ";
    print_r($a);
    $b = array_map(function($v){ return $v + 2 ; }, $a);
    echo "<br>B Result : ";
    print_r($b);
?>

multidimensional array time use below code

<?php 
    echo "<pre>";
    // multidimensional array time use below code
    $a1 = ["id" => 4,"name" => 3];
    echo "<br>A1 Input : ";
    print_r($a1);
    $b1 = array_map(function($v){ return $v + 2 ; }, array_values($a1));
    echo "<br>B1 Result : ";
    print_r($b1);
    
?>
JD Savaj
  • 803
  • 8
  • 16
  • Please add some explanation to your code such that others can learn from it. For example, why do you need `array_values`? – Nico Haase Oct 08 '20 at 10:53