Reputation: 5544
In php, would the function count work also on a JSON object? Will it return the number of elements in the object? Or does this function only work for an array?
count($varJSONobject);
Upvotes: 0
Views: 759
Reputation:
There's no such thing as a JSONobject
in PHP (unless it's some user-defined something or other). There are only arrays or stdClass
instances generated by json_decode
docs, which can be used with count
.
It's possible to make an object respond to count
by having the object implement the Countable
docs interface.
For the sake of completeness, consider the following count
results:
$test = new stdClass;
$test->prop1 = 1;
$test->prop2 = 1;
var_dump(count($test)); // 1
$test = (array) $test;
var_dump(count($test)); // 2
class CountTest {
public $prop1 = 1;
public $prop2 = 1;
}
$test = new CountTest;
var_dump(count($test)); // 1
$test = (array) $test;
var_dump(count($test)); // 2
// class implementing Countable
class CountMe implements Countable {
protected $myCount = 3;
public function count(){
return $this->myCount;
}
}
$test = new CountMe;
var_dump(count($test)); // 3
Upvotes: 3