Sergio Teixeira Sergio Teixeira - 14 days ago 7
PHP Question

Count specific array values starts something

i have this array:

$array = array("pg_1","pg_2","pg_3","pg_4","pg_5","qr_1","qr_2","qr_3");


I want to count the values which is starts with pg.

So far i have tried below code :

$arraycount = array_count_values($array);

$countpg = $arraycount['pg%'];


I forgot that I have keys and values:

$array = Array ( [pg_1] => 2 [pg_2] => 3 [pg_3] => 2 [pg_4] => 4 [pg_5] => 1 [gp_1] => 1 [gp_2] => 4 [gp_3] => 3 )

Answer

If value contains pg, then increment $i

$array = array("pg_1","pg_2","pg_3","pg_4","pg_5","qr_1","qr_2","qr_3");
$i = 0;

foreach ($array as $value) {
    if (strpos($value, 'pg') !== false) { 
       $i++;
    }
}
echo $i;
Comments