0

I am working with php,I have associative array and i want to count total number of array (using loop) whose key is "IsRatingQuestion" and value is ="1" Here is my array

Array
(
    [0] => Array
        (
            [ques_id] => 2
            [question] => Please enter your mobile number.
            [IsRatingQuestion] => 0
            [ISSubQuestion] => 
            )

    [1] => Array
        (
            [ques_id] => 2
            [question] => Lorem Ipsum dummy text
            [IsRatingQuestion] => 
            [ISSubQuestion] => 
            )

    [2] => Array
        (
            [ques_id] => 15
            [question] => Would your recommend TOSSIN ?
            [IsRatingQuestion] => 1
            [ISSubQuestion] => 
            )

    [3] => Array
        (
            [ques_id] => 18
            [question] => which type of mobile you have ?
            [IsRatingQuestion] =>1 
            [ISSubQuestion] => 1
            )

Here is my php code ( Right now counting all records/array),i want to count array whose key is "IsRatingQuestion" and value is ="1",How can i do this ? Thanks in advance.

<?php   
    $count=count($rec);
    for ($j = "2"; $j < $count+"1"; $j++)
                        {
?>
    <li>Step <?php echo $j; ?></li>
<?php } ?>

3 Answers3

1

you can use array_filter function to filter item which IsRatingQuestion=1

$filterdArray = array_filter($rec,function($item){
    if($item['IsRatingQuestion']==1){
        return $item;
    }
});
count($filterdArray)
nay
  • 1,725
  • 1
  • 11
  • 11
0

Iterate through the array, and check to see if it equals 1, if it does add to your counter; Example:

$count = 0;
foreach($yourArray as $val){
    if(isset($val['isRatingQuestion']) && $val['IsRatingQuestion'] === 1){
        $count++;
    }
}
echo $count;
# Output: 2
Crimin4L
  • 610
  • 2
  • 8
  • 23
0

You can keep a counter, iterate over the array and, when the condition is true, add to the counter.

$count = 0;
foreach($entries as $entry) {
    if (isset($entry['isRatingQuestion']) && $entry['isRatingQuestion'] === 1) {
        $count ++;
    }
}
echo "$count entries match the condition";
Raul Sauco
  • 2,645
  • 3
  • 19
  • 22