6

I have an array like this:

$a = array('aa', 'bb', 'cc', 'dd');

I want to add the 'rq' string at the beginning of all the elements of the array. Is it possible to do it by calling array_map() on this array?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hd.
  • 17,596
  • 46
  • 115
  • 165

3 Answers3

14
$a = array_map(function ($str) { return "rq$str"; }, $a);
deceze
  • 510,633
  • 85
  • 743
  • 889
3
function addRq($sValue) {
    return 'rq'.$sValue;
}
$newA = array_map("addRq", $a);

Also see this example.

scessor
  • 15,995
  • 4
  • 43
  • 54
2

You can have it like this:

<?php
    $a = array('aa', 'bb', 'cc', 'dd');
    $i=0;
    foreach($a as $d) {
        $a[$i] = 'rq'.$d;
        $i++;
    }
    var_dump($a);
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2hamed
  • 8,719
  • 13
  • 69
  • 112