1

I have this in my DB: 3,14,12,13

Called $user['buddylist']

And this is my code, but the output is 1 instead of 4, What's wrong?

$prefix = '"';
$tag = explode( ',', $user['buddylist'] );
$foll = $prefix . implode( '",' . $prefix, $tag ) . '",';
$following = array($foll );
$nr = count($following);

The output of $foll is "3","14","12","13", :/

1 Answer 1

2

Because foll is a string when you do this:

$foll = $prefix . implode( '",' . $prefix, $tag ) . '",';

You are creating an array with one element when you do this:

$following = array($foll );

If you want to count, you need to count the array before you turn it into a string:

$prefix = '"';
$tag = explode( ',', $user['buddylist'] );
$nr = count($tag);
$foll = $prefix . implode( '",' . $prefix, $tag ) . '",';
$following = array($foll );

I would probably code it like this:

class Buddies {
     private $buddies;
     public function __construct($buddy_list_string) {
         $this->buddies = explode( ',', $buddy_list_string);
     }
     public function count() {
         return count($this->buddies);
     }
     public function __toString() {
         return '"' . implode('","', $this->buddies) . '"';
     }
     public function toArray() {
         return $this->buddies;
     }
}

$buddies = new Buddies($user['buddylist']);
echo $buddies->count(); //4
echo $buddies; //"3","14","12","13"
foreach($buddies->toArray() as $buddy) {
     //do stuff
}
1
  • so just I need this: $tag = explode( ',', $user['buddylist'] ); $nr = count($tag); ? :S Aug 28, 2014 at 18:24

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.