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

Jens
69.6k15 gold badges107 silver badges133 bronze badges
asked Aug 28, 2014 at 18:15

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
}
answered Aug 28, 2014 at 18:19
Sign up to request clarification or add additional context in comments.

1 Comment

so just I need this: $tag = explode( ',', $user['buddylist'] ); $nr = count($tag); ? :S

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.