explode + count_chars -

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
frenchyarnaud
New php-forum User
New php-forum User
Posts: 3
Joined: Tue Mar 06, 2018 12:59 pm

Tue Mar 06, 2018 1:13 pm

Hi guys,

I am stranded on a very simple thing : counting ocurences in a string. Sounds simple enough, but I must have a brain knot because I have been blocked with this for several hours now.

So say I have a string of integers separated by : , like so :

Code: Select all

$stringOfInts = "1:3:3:5:12:26:7:5:10:2:2:2";
Note that those ints CAN be 0 to 999. Now I need to return the count for each int, along the lines of

Code: Select all

1 => 1
2 => 3
3 => 2
5 => 2
7 => 1
10 => 1
12 => 1
26 => 1
Of course

Code: Select all

foreach (count_chars($data, 1) as $i => $val) {/*do whatever*/}
does not work simply because the ints have several digits possibly - and I can't know how many. So the FOREACH loop returns that the int 26 is one 2 and one 6, not 26.

If anyone has a lead, this would be SO MUCH appreciated ! I am sure it's dead simple, but I just can't figure it out...

Signed : a middle-aged french pulling his last hair.

User avatar
phpRob
New php-forum User
New php-forum User
Posts: 65
Joined: Mon Feb 26, 2018 7:15 am

Tue Mar 06, 2018 2:07 pm

When you are baffled with an array challenge you should always look at the php online docs manual. This array function is the only call you need to make and you are done:
http://php.net/manual/en/function.array ... values.php

User avatar
hyper
php-forum Fan User
php-forum Fan User
Posts: 708
Joined: Mon Feb 22, 2016 5:52 pm

Tue Mar 06, 2018 2:15 pm

The answer can be simple or complicated, it's up to you

Your code here:

Code: Select all

1 => 1
2 => 3
3 => 2
5 => 2
7 => 1
10 => 1
12 => 1
26 => 1
is very close to an answer.

additional hint:

Code: Select all

$freq[1] = 2;
$freq[17] = 12;
$freq[4] = 5;
$freq[999] = 19;
print_r($freq);

frenchyarnaud
New php-forum User
New php-forum User
Posts: 3
Joined: Tue Mar 06, 2018 12:59 pm

Tue Mar 06, 2018 2:18 pm

Thank you to the both of you. As soon as I read the word "array" it was solved... I just converted the string into an array with a simple loop and voilà! Solved after what I can only qualify as a major brain freeze...

Post Reply