Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Adding prefix strings to array values

Tags:

arrays

php

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.

like image 281
skeggse Avatar asked Dec 26 '10 23:12

skeggse


2 Answers

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'; } );
like image 128
Andre Avatar answered Nov 12 '22 21:11

Andre


Use array_map()

$array = array('a', 'b', 'c');
$array = array_map(function($value) { return ' '.$value; }, $array);
like image 29
shfx Avatar answered Nov 12 '22 20:11

shfx