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
1 Answer 1
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
dave
65.1k6 gold badges81 silver badges98 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Jonathan Nungaray
so just I need this: $tag = explode( ',', $user['buddylist'] ); $nr = count($tag); ? :S
lang-php