I have the following function in PHP where an array stores data in a loop. I have it conditioned that if the amount is less than 0 it adds the code and the amount to the array
But I would like to ask first if the code exists in my array, so this decreases the amount to the code already existing in the array.
To find an element within an array is array_search
but I don't know how to condition it to add the quantity to that element
$array_bpt = array();
$codpza = '001';
$cantidad = 10;
/*Agrega codigo 001 a array*/
$stock = stock($codpza, $cantidad,$array_bpt);
$array_bpt = $stock ["array_bpt"];
$codpza = '001';
$cantidad = 4;
/*Codigo ya encontrado en array disminuye 4 */
$stock = stock($codpza, $cantidad,$array_bpt);
$array_bpt = $stock ["array_bpt"];
echo $array_bpt (0) => Array
(
(codpza) => '001',
(cantidad) => 6
)
function stock($codpza, $cantidad,$array_bpt = array())
{
if ($cantidad_bpt>0) {
/*Preguntar si existe codigo en array*/
//$found_key = array_search($codpza, array_column($array_bpt , 'codpza'));
array_push($array_bpt, array(
"codpza" => $codpza,
"cantidad" => $cantidad
));
}
$out['array_bpt'] = $array_bpt;
return $out;
}
You're almost done, just uncomment the search line and parse the return value, keeping in mind that it can return false or an integer.
It must be compared strictly, using 3 signs
===
because:Check the documentation to see what other values can be interpreted as false in a loose comparison.