<?php echo count($_SESSION['cart']); ?>
I'm trying to count array data in PHP session and it works great, but if there is no data yet in the session, it returns empty and warnings. How to make it return 0 instead?
Should I use if statement?
You can use the null coalescing operator and use an empty array as default:
<?php echo count($_SESSION['cart'] ?? []);
Another alternative is to just normalise session data whenever you create it for the first time. That makes everything easier because you can omit repetitive checks:
<?php
session_start();
if (!$_SESSION) {
$_SESSION['cart'] = [];
}
echo count($_SESSION['cart']);
session_start()before.