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?
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.
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 .
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.
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).
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
.
Simple:
foreach ($array as &$value) { $value *= (-1); } unset($value);
Unless the array is a string:
foreach ($array as &$value) { $value = '-' . $value; } unset($value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With