Alex Rivera | Logout

Add prefix string to each value of a flat array

Asked 2010-12-26T23:25:43.757
31

What is the best way to add a specific value or values to an array?

<?php
$myarray = array("test", "test2", "test3");
$myarray = array_addstuff($myarray, " ");
var_dump($myarray);
?>

Which outputs:

array(3) {
  [0]=>
  string(5) " test"
  [1]=>
  string(6) " test2"
  [2]=>
  string(6) " test3"
}

You could do so like this:

function array_addstuff($a, $i) {
    foreach ($a as &$e)
        $e = $i . $e;
    return $a;
}

But I'm wondering if there's a faster way, or if this function is built-in.

Edit
Report

1 Answer

35

Use array_map()

$array = array('a', 'b', 'c');
$array = array_map(function($value) { return ' '.$value; }, $array);
answered 2010-12-27T14:24:32.873

Your Answer