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. Commented Feb 23, 2015 at 10:35
  • 1
    Use, for example, $exploded = explode(' ', $mynumbers); echo 'There are '.count($exploded).' numbers in your variable.'; 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
Sign up to request clarification or add additional context in comments.

3 Comments

Can you explain what "/\d+/" does?
@Lin For sure! It's a regex and \d matches [0-9], the quantifier + -> is for one to unlimited times (greedy)
@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)
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

Comments

2

Use explode() for example:

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

Comments

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.