ScottD ScottD - 8 months ago 37
PHP Question

Count number of values in array with variables

I'm trying to count the number of times a certain value turns up in an array. Except this value will always increment by 1, and there is an unknown number of these values in the array.


$first = array( 'my-value-1','my-value-2','my-value-3' );

$second = array( 'my-value-1','my-value-2','my-value-3', 'my-value-4', 'my-value-5' );

My goal is to be able to retrieve a count of 3 for
and a count of 5 for
in the example above.

There may be other values in the array, but the only values I'm interested in counting are the ones that start with

I won't know the number of the values in the array, but they will always start with
with a number added to the end.

Is there a way to count the number of times
shows up in the array with some sort of wildcard?


Use a regex to filter the array and count the values that match. You could also use ^ to force it to be at the beginning ^my-value-\d+:

$count = count(preg_grep('/my-value-\d+/', $first));

You could also do it this way. Again you could use === 0 instead to make it match at the beginning:

$count = count(array_filter($first, function($v) {
                                        return strpos($v, 'my-value-') !== false;