php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #43538 count on non-array should return false, not 1
Submitted: 2007-12-08 20:30 UTC Modified: 2008-07-16 11:07 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: warren at transfusionmedia dot com Assigned:
Status: Not a bug Package: Feature/Change Request
PHP Version: * OS: *
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: warren at transfusionmedia dot com
New email:
PHP Version: OS:

 

 [2007-12-08 20:30 UTC] warren at transfusionmedia dot com
Description:
------------
When doing count($var) where $var is not an array, the return = 1.

The problem is when you're doing a check in your code:

if (count($var) > 0){
  //do something
}

This will evaluate as true if $var is not an array. This is a problem if you are doing this:

if (count($var) > 0){
    sort($var); // anything that requires $var to be an array
}

If there is anything in that if statement that requires $var to be an array, there will be a fatal error. I know you can also add an is_array check in there, but that is non-obvious and shouldn't be necessary.

Really, if $var is not an array, count($var) should return false or null, or at least a -1

Reproduce code:
---------------
$var = "foo";

if (count($var) > 0){
  sort($var);
} else {
  echo "The value of var is not greater than zero";
}

Expected result:
----------------
The value of var is not greater than zero

Actual result:
--------------
Warning: sort() expects parameter 1 to be array, string given

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-07-16 00:32 UTC] kalle@php.net
Seems odd why its coded to return 1 imo, heres a patch against latest PHP_5_3 cvs that changes this to return false:
http://www.phpfi.com/332583
 [2008-07-16 11:07 UTC] helly@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

It returns 1 as that means you have one element.

Anyway this is the expected behavior and used by all our users for about 10 years now. Changing this will break most PHP applications out there. Further more the scenarios shown should use is_array() and family of funtions.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 26 06:01:32 2024 UTC