Reputation: 397
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?
Upvotes: 2
Views: 2464
Reputation: 144
Try using $matches[0] instead of $matches (returns 7).
Then if you want to sum all the numbers you can use the foreach function
Upvotes: 0
Reputation: 19662
This is due to the way preg_match_all returns results. Its main array elements are the preg brackets (expression matches), whilst the contents of them are what you matched.
In your case, you have no sub-expressions. The array will therefore only have one element - and that element will contain all your digits.
To sum them up, simply do this:
$sum = 0;
$j = count($matches[0]);
for ($i = 0; i < $j; ++$i) {
$sum += (int)$matches[0][$i];
}
Upvotes: 0
Reputation: 46987
The result of preg_match_all
is actually an array of an array:
Array
(
[0] => Array
(
[0] => 9
[1] => 5
[2] => 6
[3] => 3
[4] => 4
[5] => 5
[6] => 2
)
)
So you'll need to do something like:
echo "Array size: " . count($matches[0]);
echo "Array sum: " . array_sum($matches[0]);
Upvotes: 3
Reputation: 437336
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
)
)
Upvotes: 4