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.

0

5 Answers 5

52

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'; } );
Sign up to request clarification or add additional context in comments.

3 Comments

whats the & before the $value for?
@GDY: it means you're passing this parameter by reference and not by value (default behaviour) php.net/manual/en/language.references.pass.php
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;?
35

Use array_map()

$array = array('a', 'b', 'c');
$array = array_map(function($value) { return ' '.$value; }, $array);

1 Comment

Wouldn't this have the overhead of creating a whole new array?
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 ) 

2 Comments

Please add some explanation. As you have used variable names and literals which have no correspondence with the question, that is the least you could do.
What I have to add prefix at start and end of value?
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.

Comments

2

PHP already has a native function to replace your array_addstuff() function and it doesn't need regex --substr_replace().

Starting from the 0 offset, replace 0 characters with a space.

Code: (Demo)

$myarray = ["test", "test2", "test3"];

var_export(
    substr_replace($myarray, ' ', 0, 0)
);

Output:

array (
  0 => ' test',
  1 => ' test2',
  2 => ' test3',
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.