Jonathan Nungaray
Jonathan Nungaray

Reputation: 43

Count number of elements in array

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", :/

Upvotes: 1

Views: 79

Answers (1)

dave
dave

Reputation: 64657

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
}

Upvotes: 2

Related Questions