PHP count value in array

I have a code like this:

<?php if(isset($global_info_results)): ?>
   <?php echo count($global_info_results) ?>
   <span>Mali Oglasi: </span>
   <?php foreach ($global_info_results as $result) : ?>
      <?php if($result->info_type_id == 1) : ?>
         <p><?php echo $result->name?></p>
      <?php endif ?>
   <?php endforeach; ?>
<?php endif ?>

How can I calculate a specific value inside an array (for example, I want to calculate how much result it has info_type_id == 1).

+3
source share
2 answers
  <?php $a = 0
   foreach ($global_info_results as $result)
    if($result->info_type_id == 1)
      { $a = $a + 1}
     End Foreach?>

  <span>Mali Oglasi: </span>
  <?php foreach ($global_info_results as $result) : ?>
      <?php if($result->info_type_id == 1) : ?>
         <p><?php echo $result->name?></p>
+3
source

You can use array_filter to create an array of values ​​that match the criteria that you want to calculate, and then run the count on the result. The following example returns the number of elements in an array with a value greater than 4:

$items = array (1, 2, 3, 4, 5, 6, 7, 8, 9);
$itemsOfInterest = array_filter ($items, function ($elem) {return ((int) $elem > 4);})
echo (count ($itemsOfInterest));
+2
source

All Articles