Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_map and append string to elements of an array

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?

like image 720
hd. Avatar asked Jan 14 '12 08:01

hd.


People also ask

What is the use of array_map in PHP?

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.

What exactly is the the difference between array_map Array_walk and Array_filter?

The resulting array of array_map has the same length as that of the largest input array; array_walk does not return an array but at the same time it cannot alter the number of elements of original array; array_filter picks only a subset of the elements of the array according to a filtering function.

Does array map preserve keys?

The returned array will preserve the keys of the array argument if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys.

Does PHP have a map function?

Definition and Usage. The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function.


1 Answers

$a = array_map(function ($str) { return "rq$str"; }, $a);
like image 109
deceze Avatar answered Oct 27 '22 01:10

deceze