94

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?

0

8 Answers 8

174

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.

Sign up to request clarification or add additional context in comments.

10 Comments

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).
is there any way to add a suffix?
@Avik To add a suffix just use the $ anchor: preg_filter('/$/', '_suffix', $array);
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 :)
Thanks, this is the best answer, but I prefer preg_replace by the way.
|
113

Simple:

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

Unless the array is a string:

foreach ($array as &$value) {
    $value = '-' . $value;
}
unset($value);

6 Comments

Nice. The pass by reference is essential.
@Peter Ajtai Essential, but also very dangerous. You should always deactivate the referenced variable: foreach ($array as &$value){ /* ... */ } unset($value);.
@PeterAjtai Good catch, even though this has 57 votes I went ahead and updated the answer with your suggestion.
@mgutt 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.
How can an array be a string (a scalar)? Do you mean that the array contains strings?
|
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

3 Comments

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.
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.
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; });
28

Something like this would do:

array_map(function($val) { return -$val;} , $array)

1 Comment

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.
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

Comments

6
$array = [1, 2, 3, 4, 5];
$array=explode(",", ("-".implode(",-", $array)));
//now the $array is your required array

2 Comments

Its a single line solution. What type of explanation do you want ?
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.
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)

Comments

1

You can also do this since PHP 7.4:

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

Live demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.