Añadir un prefijo a cada elemento de una matriz PHP


Tengo una matriz PHP de números, que me gustaría prefijar con un menos (-). Creo que a través del uso de explotar e implosionar sería posible, pero mi conocimiento de php no es posible realmente hacerlo. Cualquier ayuda sería apreciada.

Esencialmente me gustaría partir de esto:

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

A esto:

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

¿Alguna idea?

Author: Dávid Horváth, 2011-10-01

6 answers

Simple

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

A menos que el array sea una cadena:

foreach ($array as &$value) {
    $value = '-'.$value;
}
unset($value);
 86
Author: Rohit Chopra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-19 20:48:36

Una forma elegante de prefijar valores de array (PHP 5.3+):

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

Además, esto es más de tres veces más rápido que un foreach.

 84
Author: Dávid Horváth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-23 17:51:22

En este caso, la respuesta de Rohit es probablemente la mejor, pero el PHP array functions puede ser muy útil en situaciones más complejas.

Puede utilizar array_walk() realizar una función en cada elemento de un array alterando el array existente. array_map() hace casi lo mismo, pero devuelve una nueva matriz en lugar de modificar uno existente, ya que parece que quieres seguir utilizando la misma matriz, se debe utilizar array_walk().

A trabajar directamente en los elementos de la matriz con array_walk(), pase los elementos de la matriz por referencia (function(&$item)).

Desde php 5.3 puede usar la función anónima en array_walk:

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

Ejemplo de Trabajo

Si php 5.3 es un poco demasiado elegante para usted, simplemente use createfunction():

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

Ejemplo de Trabajo

 62
Author: Peter Ajtai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:15

Algo como esto haría:

array_map(function($val) { return -$val;} , $array)
 20
Author: JRL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-01 01:55:10
$array = "1, 2, 3, 4";
$array = explode( ',', $array );
foreach ($array as &$value){
    $value = '-' . trim($value);
}
$array = implode(', ', $array);   //output "-1, -2, -3, -4"
 4
Author: BomAle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-21 04:31:10
$array = [1, 2, 3, 4, 5];
$array=explode(",", ("-".implode(",-", $array)));
//now the $array is your required array
 0
Author: SarwarCSE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-27 13:02:07