I want to count specific strings from array values
$array = array("report=D","report=D","report=D","report=I","report=I");
I am going to count the number of D
,U
& I
, as well as their meanings.
D = Delivered
U = Undelivered
I = Invalid
I am expecting an output of:
D = 3
U = 0
I = 2
First, I replace "report="
using str_replace()
, then array_filter
is used to count specific values.
<?php
$array = array(
"report=D","report=D","report=D","report=I","report=I"
);
$array = str_replace("report=","",$array);
function getting_u($n) { return $n == "U"; }
function getting_d($n) { return $n == "D"; }
function getting_i($n) { return $n == "I"; }
$result_of_u = array_filter($array, "getting_u");
$result_of_d = array_filter($array, "getting_d");
$result_of_i = array_filter($array, "getting_i");
print_r($result_of_u);
print_r($result_of_d);
print_r($result_of_i);
echo "Count of U = ".count($result_of_u);
echo "\n";
echo "Count of D = ".count($result_of_d);
echo "\n";
echo "Count of I = ".count($result_of_i);
?>
See a working code here.
The code seems to work fine for me, but I'm concerned whether this is the correct/best method of procedure.
I am also unsure if my code contains any strange behaviour or present/future problems.