While others have explained why your solution currently does not work, and some ways around it, the best alternative is to loop the entire array until you find 5 matches - by using a foreach-loop instead.
By using an foreach-loop, you will never run into issues if the array has less than 5 matching elements (if it has less than 5 matching elements, it will never break).
$i = 0;
// Loop the array
foreach ($counselor as $k=>$v) {
// Check if there is a match
if ($v->state == $state || !$state) {
// Do whatever if a match here
$i++;
}
// If we have found 5 matches, break out of the loop!
if ($i == 5) {
break;
}
}
You can now check how big $i is, and if less than 5, you found less than 5 matches. If it's exactly 5, you found your matches, and ended the loop.
var_dump($counselor[$i]->state,$state)without using if-else block inside the loop for let saywhile(count($counselor))