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?
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);
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
.
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;
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;
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)
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"
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
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