-2

I want to add +2 to an array elements without looping(foreach).

$arr=array(5,6,8,0,55,64,1);

wanted output:

$arr=array(7,8,10,2,57,66,3)
9
  • 1
    Have you considered using a for or foreach loop? Commented May 25, 2013 at 9:49
  • 2
    php.net/manual/en/function.array-map.php Commented May 25, 2013 at 9:50
  • 1
    can you tell me why exactly you want to do that? I mean whats your point? Commented May 25, 2013 at 9:50
  • No. I need output without using for and foreach Commented May 25, 2013 at 9:51
  • foreach($a as $arr) {$arr[$a] += 2; } from AQ Commented May 25, 2013 at 9:51

3 Answers 3

3

Then array_map is you friend :

function foo($n) { return($n + 2); }
$arr = array(5,6,8,0,55,64,1);
$ouput = array_map("foo", $arr);

EDIT after the answer of Gautam3164 : array_walk is also an option, indeed. Just dont forget that array_map returns a new array when array_walk takes a reference and updates your array.

Sign up to request clarification or add additional context in comments.

3 Comments

nice. thanks gautam too.
Yes @Herode you are right..I didnt gave array_map only bec of this only
Anyway good ans of yours too.
2
// PHP 5.3+ anonmymous function.
$output = array_map(function($val) { return $val+2; }, $arr);

Comments

1

Try this

array_walk($array, function(&$item) { $item += 2; });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.