array_map and append string to elements of an array
Asked Answered
M

3

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?

Manner answered 14/1, 2012 at 8:43 Comment(1)
You mean 'prepend'...Billposter
J
14
$a = array_map(function ($str) { return "rq$str"; }, $a);
Jemy answered 14/1, 2012 at 8:55 Comment(0)
B
3
function addRq($sValue) {
    return 'rq'.$sValue;
}
$newA = array_map("addRq", $a);

Also see this example.

Bohi answered 14/1, 2012 at 8:54 Comment(0)
T
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);
?>
Trigonal answered 14/1, 2012 at 8:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.