Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a prefix to each item of a PHP array

I have a PHP array of numbers, which I would like to prefix with a minus (-). I think through the use of explode and implode it would be possible but my knowledge of php is not possible to actually do it. Any help would be appreciated.

Essentially I would like to go from this:

$array = [1, 2, 3, 4, 5]; 

to this:

$array = [-1, -2, -3, -4, -5]; 

Any ideas?

like image 229
MBL Avatar asked Oct 01 '11 01:10

MBL


People also ask

What is Array_keys () used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

Does += work on arrays in PHP?

The + operator in PHP when applied to arrays does the job of array UNION. $arr += array $arr1; effectively finds the union of $arr and $arr1 and assigns the result to $arr .

How do you add numbers to an array in PHP?

PHP array_push() function is used to insert new elements into the end of an array and get the updated number of array elements. You may add as many values as you need. Your added elements will always have numeric keys, even if the array itself has string keys.

Can you add to an array in PHP?

Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).


2 Answers

An elegant way to prefix array values (PHP 5.3+):

$prefixed_array = preg_filter('/^/', 'prefix_', $array); 

Additionally, this is more than three times faster than a foreach.

like image 151
Dávid Horváth Avatar answered Sep 29 '22 10:09

Dávid Horváth


Simple:

foreach ($array as &$value) {    $value *= (-1); } unset($value); 

Unless the array is a string:

foreach ($array as &$value) {     $value = '-' . $value; } unset($value); 
like image 35
Rohit Chopra Avatar answered Sep 29 '22 10:09

Rohit Chopra