James Allan James Allan - 1 month ago 9
PHP Question

Counting sessions in a foreach loop in not working PHP

I am trying to count all my products that is stored in a session called

$_SESSION['product'.$id];
.
But its not counting, its counting like this 1 1 1 1.
So its counting 1 of each product id separated.
My foreach loop...

foreach ($_SESSION as $name => $value) {
if($value > 0){
if(substr($name, 0, 8 ) == "product_"){
$length = strlen($name) -8;
$item_id = substr($name,8 , $length);

$query = "SELECT *
FROM gallery2
WHERE gallery2.id =".escape_string($item_id). "";
$run_item = mysqli_query($conn,$query);
while($rows = mysqli_fetch_assoc($run_item)){
$vari = $rows['variante'];
$num = $rows['title'];
$id = $rows['id'];

if(!isset($_SESSION['icms'.$id])) {
$_SESSION['icms'.$id]='0';
}else{
$_SESSION['icms'.$id];
}

//some code here

$subtotal=$value * $_SESSION['icms'.$id];
$cost=$_SESSION['icms'.$id];

$product = '
<tr>
<td style="width:100px; "><img src="../'.$rows['image'].'" style="width:90%;border: 1px solid black;"></td>
<td>'.$num.''.$vari.'</td>
//some code here
<td class="product'.$id.'">'.$value.'</td>
<td class="cost" data-id="'.$id.'" >R$:'.$cost.'</td>
<td class="subtotal" data-id="'.$id.'">R$:'.number_format($subtotal, 2, '.', '') .'</td>
<td>
'.$btn_add.' '.$btn_remove.' '.$btn_delete.'
</td>
</tr>';
echo $product;
//some closing brackets


Why this is happening?
What i tried:

print_r(count($_SESSION['product_'.$item_id])) ;
print_r(count($name)) ;
print_r(count($product)) ;
print_r(count($value)) ;


enter image description here

Answer

You can use this:

$product_count = count(array_filter(array_keys($_SESSION), function($x) {
    return substr($x, 0, 8) == 'product_';
}));

But as I mentioned in a comment, it would probably be better if you redesigned your data. Instead of storing each product in a separate session variable, store them in an array. So instead of $_SESSION['product_'.$i] you would have $_SESSION['products'][$i]. Then you wouldn't need the code that checks whether the session variable beings with product_, you could just use

foreach ($_SESSION['products'] as $id => $value)

And to get the number of products, it would just be count($_SESSION['products']).