phparrayscounting

Count the elements of a subarray


Under Return Values for Count()

Returns the number of elements in var. If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned.

I have a string which is filled with letters and numbers and I'm using preg_match_all() to extract those numbers. As I recall preg_match_all fills the contents of the array given in the 3rd parameter with the results. Why does it return 1?

What am I doing wrong in my code?

$string = "9hsfgh563452";
preg_match_all("/[0-9]/",$string,$matches);

echo "Array size: " . count($matches)."</br>"; //Returns 1
echo "Array size: " . sizeof($matches)."</br>"; //Returns 1
print_r($matches);

I would like to sum the contents of the array (which is all the numbers returned in the string) array_sum() didn't work ; it is a string array and I don't know how to convert it to an int array because I'm not using any delimiters like ' , ' and such. Is there a more efficient way in doing this?


Solution

  • The count is 1 because $matches is an array which contains another array inside. Specifically, $matches[0] is an array that contains each match of the zero-th capturing group (the whole regular expression).

    That is, $matches looks like this:

    Array
    (
        [0] => Array  // The key "0" means that matches for the whole regex follow
            (
                [0] => 9   // and here are all the single-character matches
                [1] => 5
                [2] => 6
                [3] => 3
                [4] => 4
                [5] => 5
                [6] => 2
            )
    
    )