简体   繁体   中英

count(): Parameter must be an array or an object that implements Countable in codeigniter

I want to count this $maxjam variable in this code

$my_array = array(1,2,3,4,5,6);
shuffle($my_array);

foreach ($my_array as $key => $value) {
$hari = $my_array[$key];
if($hari == 5){

    $maxjam = 6;
}elseif ($hari == 6){

    $maxjam = 8;

}else{  

    $maxjam = 7;

}

$jumlahjam = count($maxjam);
print_r($jumlahjam);
echo'<br>';
}

But i get this error:

A PHP Error was encountered Severity: Warning

Message: count(): Parameter must be an array or an object that implements Countable

Filename: controllers/jadwal.php

Line Number: 166

How to solve this error?

Try this out,This method replaces all the other methods.This is because you are using a new version,you should return an array.IF YOU ARE USING CODEIGNITER ,Then just change the code as i have mentioned below

change your if (count($chkAdminExist)):

to if (count((array)$chkAdminExist)):

ps:$chkAdminExist is my variable,this may differ from yours

You are setting the $maxjam variable to be an integer therefore the count function fails. If you want to create a new array and append an new element on every iteration, use $maxjam[] = <value> .

$my_array = [1,2,3,4,5,6];
shuffle($my_array);
$maxjam = [];

foreach ($my_array as $hari) {
    if($hari == 5) {
        $maxjam[] = 6;
    } elseif ($hari == 6) {
        $maxjam[] = 8;
    } else {  
        $maxjam[] = 7;
    }

    $jumlahjam = count($maxjam);
    print_r($jumlahjam);
    echo'<br>';
}

The count function use for an array or an object, the $maxjam is integer. I'm using php 7.1 and in your code run well. but all is 1. i think you want some it

$maxjam = 0;
foreach ($my_array as $key => $value) {
    $hari = $my_array[$key];
    if($hari == 5){    
        $maxjam+= 6;
    }elseif ($hari == 6){    
        $maxjam+= 8;    
    }else{      
        $maxjam+= 7;    
    }
}
echo $maxjam;

Array type variable should be use for count function.

$my_array = array(1,2,3,4,5,6);
shuffle($my_array);$maxjam=array();
foreach ($my_array as $key => $value){
    $hari = $my_array[$key];
    if($hari == 5){  
    array_push($maxjam,6);
    }elseif ($hari == 6){a
    rray_push($maxjam,8);
    }else{ 
    array_push($maxjam,7);
    }
}
$jumlahjam = count($maxjam);
print_r($jumlahjam);
echo'<br>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM