Add a prefix to each item of a PHP array
Asked Answered
C

8

92

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?

Cinnamon answered 1/10, 2011 at 1:50 Comment(0)
S
113

Simple:

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

Unless the array is a string:

foreach ($array as &$value) {
    $value = '-' . $value;
}
unset($value);
Shortwinded answered 1/10, 2011 at 1:53 Comment(6)
Nice. The pass by reference is essential.Budbudapest
@Peter Ajtai Essential, but also very dangerous. You should always deactivate the referenced variable: foreach ($array as &$value){ /* ... */ } unset($value);.Pratt
@PeterAjtai Good catch, even though this has 57 votes I went ahead and updated the answer with your suggestion.Compensate
Why is it dangerous?Zamarripa
@Zamarripa Because PHP doesn't have block level variable scopes. If you use a variable with the same name later in the code, it will magically overwrite the content of the referenced variable.Pratt
How can an array be a string (a scalar)? Do you mean that the array contains strings?Unbeliever
T
172

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.

Tournament answered 23/1, 2015 at 17:51 Comment(10)
I find this the best answer mainly while it's so much faster. Also worth mentioning is preg_replace, it does roughly the same but it always returns a same-sized array with the unmodified item for items that doesn't match the regex. It's also a bit lighter on the version requirements (exists in PHP4 vs preg_filter which requires PHP >= 5.3.0).Caviness
is there any way to add a suffix?Tumbler
@Avik To add a suffix just use the $ anchor: preg_filter('/$/', '_suffix', $array);Pratt
For more information about regular expressions in PHP read the PCRE manual: php.net/manual/en/reference.pcre.pattern.syntax.phpPratt
thanks, i figured this out preg_filter('/^(.*?)$/', '$0*', $array), it does work, but i like yours, it is short. thanks again really appreciate the help :)Tumbler
This is awesome. It should definitly be the accepted answer for so many reasons. It is faster than a foreach, it moves the cyclomatic complexity to the internal sub-level of PHP and it can be used for prefix, suffix or change any part of the values of your array when you find a pattern to detect where the modification has to be done. I need to keep this function in my mind. Thank you.Vintager
I like this better than any other answers. I formerly use array_walk function but now I've changed to this way. Thank you so much!Summertime
can this method use array key to be the prefix of the value? I know foreach & array_walk can, but I wonder if this alsoSummertime
@TaufikNurRahmanda There are only a few functions in PHP that instantly combine keys with their values (http_build_query, for example). To my knowledge PCRE can't do this.Pratt
Thanks, this is the best answer, but I prefer preg_replace by the way.Guinness
S
113

Simple:

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

Unless the array is a string:

foreach ($array as &$value) {
    $value = '-' . $value;
}
unset($value);
Shortwinded answered 1/10, 2011 at 1:53 Comment(6)
Nice. The pass by reference is essential.Budbudapest
@Peter Ajtai Essential, but also very dangerous. You should always deactivate the referenced variable: foreach ($array as &$value){ /* ... */ } unset($value);.Pratt
@PeterAjtai Good catch, even though this has 57 votes I went ahead and updated the answer with your suggestion.Compensate
Why is it dangerous?Zamarripa
@Zamarripa Because PHP doesn't have block level variable scopes. If you use a variable with the same name later in the code, it will magically overwrite the content of the referenced variable.Pratt
How can an array be a string (a scalar)? Do you mean that the array contains strings?Unbeliever
B
76

In this case, Rohit's answer is probably the best, but the PHP array functions can be very useful in more complex situations.

You can use array_walk() to perform a function on each element of an array altering the existing array. array_map() does almost the same thing, but it returns a new array instead of modifying the existing one, since it looks like you want to keep using the same array, you should use array_walk().

To work directly on the elements of the array with array_walk(), pass the items of the array by reference ( function(&$item) ).

Since php 5.3 you can use anonymous function in array_walk:

// PHP 5.3 and beyond!
array_walk($array, function(&$item) { $item *= -1; }); // or $item = '-'.$item;

Working example

If php 5.3 is a little too fancy pants for you, just use createfunction():

// If you don't have PHP 5.3
array_walk($array,create_function('&$it','$it *= -1;')); //or $it = '-'.$it;

Working example

Budbudapest answered 1/10, 2011 at 4:0 Comment(3)
How much slower is your method compared to Rohits? I like one-liner so it would be nice to know how much "loss of speed" it will cause.Zamarripa
For simple numbers is probably faster a loop. Profile it:) In my case I needed to prefix strings before concatenating the whole array and the fastest solution was Array_walk followed by Implode.Fetish
Great solution. If you want to use previous declared var, add use($XXX) before "{ } : array_walk($rank, function(&$item) use($cpt) { if ($item >= $cpt) $item += 1; });Additament
P
28

Something like this would do:

array_map(function($val) { return -$val;} , $array)
Pericarditis answered 1/10, 2011 at 1:55 Comment(1)
Note that this is PHP 5.3+ only (due to the anonymous function), and it returns a new array instead of modifying the existing array (so print_r($array) would show $array unchanged after the above. - If you assign the returned value to $array this'll get the job done nicely.Budbudapest
I
12

You can replace "nothing" with a string. So to prefix an array of strings (not numbers as originally posted):

$prefixed_array = substr_replace($array, 'your prefix here', 0, 0);

That means, for each element of $array, take the (zero-length) string at offset 0, length 0 and replace it the prefix.

Reference: substr_replace

Itol answered 25/4, 2019 at 18:59 Comment(1)
this is a fantastic and simple solution that answers the question - thank you!Hoick
D
6
$array = [1, 2, 3, 4, 5];
$array=explode(",", ("-".implode(",-", $array)));
//now the $array is your required array
Downtrend answered 26/9, 2016 at 8:29 Comment(2)
Its a single line solution. What type of explanation do you want ?Downtrend
If any of the array contents contains a , then the resulting array will have more items than the original. This does work for the OPs case where it is just numbers.Turnedon
R
5

I had the same situation before.

Adding a prefix to each array value

function addPrefixToArray(array $array, string $prefix)
{
    return array_map(function ($arrayValues) use ($prefix) {
        return $prefix . $arrayValues;
    }, $array);
}

Adding a suffix to each array value

function addSuffixToArray(array $array, string $suffix)
{
    return array_map(function ($arrayValues) use ($suffix) {
        return $arrayValues . $suffix;
    }, $array);
}

Now the testing part:

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

print_r(addPrefixToArray($array, 'prefix'));

Result

Array ([0] => prefix1 [1] => prefix2 [2] => prefix3 [3] => prefix4 [4] => prefix5)

print_r(addSuffixToArray($array, 'suffix'));

Result

Array ([0] => 1suffix [1] => 2suffix [2] => 3suffix [3] => 4suffix [4] => 5suffix)
Redress answered 17/4, 2019 at 8:7 Comment(0)
L
1

You can also do this since PHP 7.4:

$array = array_map(fn($item) => -$item, $array);

Live demo

Leannaleanne answered 27/7, 2023 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.