[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1871
  • Last Modified:

count if in php arrays

Hi,

I have the following arrays:

array1 = ("CONTAR","CONTAR", "NO CONTAR","CONTAR","NO CONTAR","NO CONTAR");
array2 = ("100","100","103","102","100","100");

both arrays have corresponding elements associated: for example the first "CONTAR" in array1 corresponds to 100 in the array2, and so on...

I need to know how many items of 100 are related with "CONTAR", in this case the answer needs to be 2, is like countif in excel. Any idea?
0
joyacv2
Asked:
joyacv2
2 Solutions
 
gr8gonzoConsultantCommented:
<?php
$array1 = array("CONTAR","CONTAR","NO CONTAR","CONTAR","NO CONTAR","NO CONTAR");
$array2 = array("100","100","103","102","100","100");

$total = 0;
foreach($array1 as $idx => $val)
{
  if($val == "CONTAR")
  {
     $array2_value = $array2[$idx];
     if($array2_value == "100")
     {
        $total++;
     }
  }
}
echo $total . " total that are CONTAR and are also 100";
0
 
Ray PaseurCommented:
I understand the order of checking this way:
http://www.iconoun.com/demo/temp_joyacv2.php

<?php // temp_joyacv2.php
ini_set('display_errors', TRUE);
error_reporting(E_ALL);

$nums = array( "100",   "100",   "103",      "102",   "100",      "100"       );
$cons = array( "CONTAR","CONTAR","NO CONTAR","CONTAR","NO CONTAR","NO CONTAR" );

$tot = 0;
foreach($nums as $ptr => $val)
{
    if($val == 100)
    {
        if($cons[$ptr] == "CONTAR")
        {
            $tot++;
        }
    }
}
var_dump($tot);

Open in new window

0
 
joyacv2Author Commented:
both solutions work perfect! Thanks to both!
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now