Reputation: 33
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?
Upvotes: 1
Views: 11307
Reputation: 37
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
Upvotes: 3
Reputation: 494
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>';
Upvotes: 0
Reputation: 834
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;
Upvotes: 0
Reputation: 77
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>';
}
Upvotes: 0