1

How do I count numbers with php

$mynumbers="0855 468 4864 63848 1486"; //This is my variable, the pattern has to be like this, each number is separated by a space.
echo "There are 5 numbers in your variable";

It should return: 5

How do I do that, I know there's str_word_count but it only counts words not numbers.

3
  • 1
    Split the string on spaces and count the number of items you get. If you need to disregard non-numeric values (for cases such as ignorethis 123 andthis) then you could loop through each item in the result and increment a counter if they are considered to be numeric.
    – GoBusto
    Commented Feb 23, 2015 at 10:35
  • 1
    Use, for example, $exploded = explode(' ', $mynumbers); echo 'There are '.count($exploded).' numbers in your variable.';
    – lmarcelocc
    Commented Feb 23, 2015 at 10:36
  • Almost all the solutions are overkill... If You are sure that This string contains only numbers and spaces, You should count spaces and add one. If You want to have array in the future, use explode :). Commented Feb 23, 2015 at 10:54

4 Answers 4

3

This should work for you:

$str = "0855 468 4864 63848 1486";
preg_match_all("/\d+/", $str, $matches);
echo count($matches[0]);

Output:

5
3
  • Can you explain what "/\d+/" does?
    – Lin
    Commented Feb 23, 2015 at 10:38
  • 2
    @Lin For sure! It's a regex and \d matches [0-9], the quantifier + -> is for one to unlimited times (greedy)
    – Rizier123
    Commented Feb 23, 2015 at 10:40
  • @Lin I know it's just address to this one how did it. (If you got a notification it's because my comment followed right under yours)
    – Rizier123
    Commented Feb 23, 2015 at 11:19
2

You can try explode() function for it as like :

$mynumbers="0855 468 4864 63848 1486";
$values = explode(" ", $mynumbers);
echo count($values);

Hope it helps

2

Use explode() for example:

$mynumbers = "0855 468 4864 63848 1486";
$exploded = explode(' ', $mynumbers); 
echo 'There are '.count($exploded).' numbers in your variable.';
0

Simple single-line resolution:

$numCount = count(array_map(function($value){return is_numeric($value);}, explode(' ', $mynumbers)));

We exlplode the string into words, then return only numeric values from the resulting array and count them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.