3

I am upgrading our Codeigniter (v. 3.1.11) site from php 5.6 to php 7.2 (currently running on localhost on my Mac). Slowly I am finding all the instances of count() usage and correcting them. It is my understanding that an array is countable, but I seem to not be able to count arrays returned by Codeigniter's result_array() function after a database call....

the following section of my controller

    $reviews = $this->reviews_model->review_details($productname);
    echo "Variable is type: ".gettype($reviews);
    if (count($reviews >=1)) {
        $myreview=$reviews[0];
    } else {
        $myreview=0;
    }
    return $myreview;

calls this function in my model (note that I am echoing out the variable type just to be sure!)

    function review_details($pagename) {
    $r = false;
    $sql = "select Reviews.*, ReviewItemLink.Item as Product, ReviewItemLink.* from Reviews LEFT JOIN ReviewItemLink ON Reviews.ReviewItemID=ReviewItemLink.ReviewItemID where pagename=? AND ReviewActive = 1 ORDER BY Date DESC";
    $query = $this->db->query($sql, $pagename);
    if ($query->num_rows() > 0):
        $r = $query->result_array();
    endif;
    return $r;
}

And even though the variable is an array

Variable is type: array

I still get the by now, oh-so-familiar warning message:

Severity: Warning
Message: count(): Parameter must be an array or an object that implements Countable
Filename: controllers/Software.php
Line Number: 1005

Backtrace:

File: /Users/juner/Sites/html/application/controllers/Software.php
Line: 1005
Function: _error_handler
File: /Users/juner/Sites/html/application/controllers/Software.php
Line: 75
Function: _get_my_review

File: /Users/juner/Sites/html/index.php
Line: 324
Function: require_once

Are there types of arrays that are NOT countable? Any suggestions/ideas would be most helpful!

1 Answer 1

4

This part is incorrect (typo?):

if (count($reviews >=1)) {
    $myreview=$reviews[0];
} else {
    $myreview=0;
}

You are passing a boolean to the count function. count($reviews >=1) turns to count(true); which is why you got your warning.

if (count($reviews >=1)) { should be if (count($reviews) >=1 ) {

Sign up to request clarification or add additional context in comments.

2 Comments

Oh - good heavens! what a silly mistake. Yes - that correction allows it to be counted. But It does make me wonder how this worked for years on 5.6!
In PHP 5.6, count(true) gives you 1 due to type coercion. So in your case it returned 1 and allowed the loop to continue.

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.