count() 함수 사용 시 배열이나 객체가 아닌 값을 체크하려고 할 때 발생하는 Warning 메시지
if (is_array($data) && count($data) > 0) {
// 배열 처리 로직
}
if (is_countable($data) && count($data) > 0) {
// 배열 또는 Countable 객체 처리
}
function safeCount($data): int {
return is_countable($data) ? count($data) : 0;
}
class MyCollection implements Countable {
private $items = [];
public function count(): int {
return count($this->items);
}
}
$array = (array) $object;
$count = count($array);
$count = ($data !== null && is_array($data)) ? count($data) : 0;
function processArray(array $data): int {
return count($data);
}
// 배열 처리
$users = ['John', 'Jane', 'Bob'];
if (is_array($users) && count($users) > 0) {
foreach ($users as $user) {
echo $user . "\n";
}
}
// 객체 처리
$collection = new MyCollection();
if ($collection instanceof Countable) {
echo count($collection);
}