1

I am using PHP 7.4 and my class have a function that should return an array. But if the row is empty it returns false instead of an empty array. That is why I get an error message:

Return value must be of type array, bool returned

private function getCartItem(int $sku): array
{
    $statement = $this->pdo->prepare("SELECT * FROM pbo_cartItem WHERE cartId = ? AND sku = ?");
    $statement->execute(array($this->cartId, $sku));
    return $statement->fetch(PDO::FETCH_ASSOC);
}
1
  • 2
    fetch() returns false on failure, like when there are no available rows. It's up to you to handle this and generate a blank array if you need it. Something like return $statement->fetch(PDO::FETCH_ASSOC) ?: [];. Also note that fetch() only returns one (the next) row. If you have multiple rows, you need to keep calling fetch() until it returns false (meaning you ran out of rows). Did you want fetchAll() instead? Commented Jan 22, 2021 at 20:27

1 Answer 1

4

The PDOStatement::fetch() method returns false if there are no more rows in the result set.

To overcome this error message, provide an empty array as a default value in case no rows were found.

return $statement->fetch(PDO::FETCH_ASSOC) ?: [];
Sign up to request clarification or add additional context in comments.

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.