0

<?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?

3
  • which working do you getting ? Commented Apr 19, 2020 at 11:16
  • Doesn't look like you have session_start() before. Commented Apr 19, 2020 at 11:19
  • We can figure out the warning message, but that's normally not a good reason to omit it from the question. Error messages are diagnostic information to help coding. Commented Apr 19, 2020 at 11:29

3 Answers 3

2

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']);
Sign up to request clarification or add additional context in comments.

Comments

0
$result = isset($_SESSION['cart']) ? count($_SESSION['cart']) : 0;
echo $result;

Comments

0

You need to start the session first and should always use isset() on unknown variables (or keys of arrays).

<?php
session_start();

echo isset($_SESSION['cart'])
    ? count($_SESSION['cart'])
    : 0;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.