There is some php method that resembles the indexof, push and reduces [closed]

2

Good to know if in php there is something similar to indexof, push and reduce javascipt

    
asked by rosibel vicent 05.10.2017 в 16:51
source

1 answer

1

indexOf ~ array_search()

$array = array(0 => 'azul', 1 => 'rojo', 2 => 'verde', 3 => 'rojo');

$clave = array_search('verde', $array); // $clave = 2;
$clave = array_search('rojo', $array);  // $clave = 1;

push ~ array_push()

$pila = array("naranja", "plátano");
array_push($pila, "manzana", "arándano");
print_r($pila);

// Resultado:
Array
(
    [0] => naranja
    [1] => plátano
    [2] => manzana
    [3] => arándano
)

reduce ~ array_reduce()

function suma($carry, $item)
{
    $carry += $item;
    return $carry;
}

function producto($carry, $item)
{
    $carry *= $item;
    return $carry;
}

$a = array(1, 2, 3, 4, 5);
$x = array();

var_dump(array_reduce($a, "suma")); // int(15)
var_dump(array_reduce($a, "producto", 10)); // int(1200), ya que: 10*1*2*3*4*5
var_dump(array_reduce($x, "suma", "No hay datos a reducir")); // string(22) "No hay datos a reducir"
    
answered by 05.10.2017 / 17:09
source