-2

I try to get value after symbol '@' and count it. But this code doesn't give the correct result. How to fix it?

$t="Hi, I invite @nina and @nana to come to my party tomorow";
$arr=explode(' ', $t);
foreach($arr as $user ) {
$result=strstr($user, '@');
$total = $count($result);
}
echo $total;

Result = 1

Expected Result =2

lolagi
  • 61
  • 1
  • 8
  • Look carefull at `@arr=explode(' ', $t);`. – PeeHaa Jun 18 '16 at 18:19
  • Also there is more wrong with your code. Please include working code (and check whether that is really the case) to your question. – PeeHaa Jun 18 '16 at 18:23
  • Every time the code loops (from `foreach`) you are assigning the count (incorrect here as `$count()` when it should be `count()`). Each time the code loops, it will assign a new value to `$total`. If you want a cumulative total, instead of `$total = count($result);`, use `$total += count($result);` At the start of the loop, before the foreach statement, initialize the value with `$total = 0;` – Chris Baker Jun 18 '16 at 18:30
  • You named it `$total`, you want to store a total in it, however you put a new value in it on each iteration. And the value you put in it is wrong, btw. – axiac Jun 18 '16 at 18:32
  • 1
    Use the return from `preg_match_all()` https://stackoverflow.com/a/23268269/2943403 – mickmackusa Oct 28 '21 at 07:43

2 Answers2

3

Why don't you explode it with @?

$t = "Hi, I invite @nina and @nana to come to my party tomorow";
$arr = explode('@', $t);
$total = count($arr) - 1;
echo $total;

EDIT: As suggested by @mickmackusa, if you want to avoid counting solitary @, you can count those on the side and then subtract.

$t = "Hi, I invite @nina and @nana to come to my party tomorow";
$arr = explode('@', $t);
$solos = explode('@ ', $t);
$total = count($arr) - 1 - count($solos);
echo $total;
Marc Compte
  • 4,579
  • 2
  • 16
  • 22
0

Try this code.

$t="Hi, I invite @nina and @nana to come to my party tomorow";
$arr=explode(' ', $t);
$total =0;
foreach($arr as $user ) {
$result=strstr($user, '@');
$total = $count($result);
$total++;
}
echo $total;
Ayuktia
  • 431
  • 3
  • 11
  • This code-only answer was not tested and will not work. Why is it upvoted? This answer is wasting the time of researchers. – mickmackusa Oct 28 '21 at 07:35