25

What is the best way to add a specific value or values to an array? Kinda hard to explain, but this should help:

<?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.

Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
skeggse
  • 6,103
  • 11
  • 57
  • 81

4 Answers4

49

In the case that you're using a PHP version >= 5.3:

$array = array('a', 'b', 'c');
array_walk($array, function(&$value, $key) { $value .= 'd'; } );
Talk Nerdy To Me
  • 626
  • 5
  • 21
Andre
  • 3,150
  • 23
  • 23
  • whats the & before the $value for? – GDY Jun 07 '19 at 07:02
  • 1
    @GDY: it means you're passing this parameter by reference and not by value (default behaviour) https://www.php.net/manual/en/language.references.pass.php – leochab Jan 13 '20 at 15:38
  • Technically, you're adding a suffix, not a prefix. Is there a more succinct way to do a prefix in the anonymous function besides `$value = ' ' . $value;`? – thelr May 11 '21 at 13:44
  • Like this one! Thank you. – Mr. Jo May 27 '21 at 14:10
31

Use array_map()

$array = array('a', 'b', 'c');
$array = array_map(function($value) { return ' '.$value; }, $array);
shfx
  • 1,261
  • 1
  • 11
  • 16
14

Below code will add "prefix_" as a prefix to each element value:

$myarray = array("test", "test2", "test3");    
$prefixed_array = preg_filter('/^/', 'prefix_', $myarray);

Output will be:

Array ( [0] => prefix_test [1] => prefix_test2 [2] => prefix_test3 ) 
AD7six
  • 63,116
  • 12
  • 91
  • 123
manish
  • 181
  • 1
  • 4
3

Use array_walk. In PHP 5.3 you can use an anonymous to define that callback. Because you want to modify the actual array, you have to specify the first parameter of the callback as pass-by-reference.

Oswald
  • 31,254
  • 3
  • 43
  • 68