My question is why this function always returns 0 after it is executed for the second time
in data I send 452, then 452 and this returns 1 but if I send data 453 or 454 or any other value it always returns 0
public function productoTemp($datos){
if (isset($_SESSION['tablaComprasTemp'])) {
$datosT=$_SESSION['tablaComprasTemp'];
for ($i=0; $i < count($datosT) ; $i++) {
$d=explode("||", $datosT[$i]);
if ($d[4]==$datos) {
return 1;
}else{
return 0;
}
}
}
}
when returning always 0 it allows me to add repeated products
echo $productoTemp=self::productoTemp($datos2);
if ($productoTemp==1){
echo json_encode($response = array('responsenum' => "-1",
'response' => "No puedes tener dos productos repetidos"));
}
$data 2 contains the product id
echo $productoTemp=self::productoTemp($datos2);
if ($productoTemp==1){
echo json_encode($response = array('responsenum' => "-1",
'response' => "No puedes tener dos productos repetidos"));
}else{
$cantidaddb=$respuesta[0]["cantidad"];
if($cantidaddb>=$datos){
$nombre=$respuesta[0]["nombre"];
$valor=$respuesta[0]["valor"];
$datos;
$datos2;
$datos3=$datos*(int)$respuesta[0]["valor"];
$articulo=$nombre."||".
$datos."||".
$valor."||".
$datos3."||".
$datos2;
$_SESSION['tablaComprasTemp'][]=$articulo;
echo json_encode($response = array('responsenum' => "1",
'response' => "Producto Agregado"));
}else{
echo json_encode($response = array('responsenum' => "-1",
'response' => "Stock no tiene suficientes productos"));
}
Trying to answer almost blindly, since I don't know what your session variable is getting, I guess it's getting a string as the variable
$datosT
I'm creating, since you use an explode and the explode converts a string to an array, so handling that logic I did the following, first to do the test I create a variable$datosT
which contains a string (taking the reference numbers 450, 451, 452, etc.), and I separate them by the character||
, I use the explode function and then in the for I do the onecount
of my variable$d
that is already an array, then inif
it I go through my array and I do the validation if$d[$i] es igual a $datosT
(which is the value that I pass as an argument that in turn is a string '452') if it finds the match it will return atrue
and when you print your functionecho productoTemp($datos);
It will print a 1 on the screen, I hope it helps you or guides you to what you want to do, good luck.