Solved

count if in php arrays

Posted on 2014-03-10
3
1,447 Views
Last Modified: 2014-03-10
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
Comment
Question by:joyacv2
3 Comments
 
LVL 34

Accepted Solution

by:
gr8gonzo earned 250 total points
ID: 39918668
<?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
 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 39918792
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
 
LVL 1

Author Closing Comment

by:joyacv2
ID: 39919048
both solutions work perfect! Thanks to both!
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question