9

How can I count the number of times a comma appears in a string such as this?

A,B,C,D

It should return "3"

0

3 Answers 3

35
substr_count($my_string, ",")

If you wish to get all the elements between commas as an array, you can always

$splitted = explode(",", $my_string)
Sign up to request clarification or add additional context in comments.

Comments

8

You could use e.g. substr_count(), or explode().

Comments

-1
$str = "A,B,C,";
echo (string)(count(explode(",",$str))-1);

count

array_explode

6 Comments

Why should anyone use two functions when there is a single native function that does the same thing?
thank you @mickmackusa , for your comment, but if you test it will return "3" as the question need is there any other answer return "3" ? .
I don't deny that it will work. It is only that you are offering a technique that has no advantages over earlier answers. I don't believe it benefits readers to learn worse ways to do something. substr_count() is the most appropriate technique. There is no compelling reason to use explode(), then count(), then subtract 1, then cast the number to a string.
I agree with you maybe the name of method you share return direct the result I can not test it as you not share example. but your option is static option that return the result it maybe you read on book , my answer made from scratch and produce the result different I reach this using code without read about it. thank you for comment really appreciate it HF.
You don't need to read any book. You only need to read the earlier answers on the page to find the easier solution. 3v4l.org/MVAMI
|

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.