2

I want to update an old PHP code, where there is used a lot of sizeof() function for empty arrays like:

<?php
$a=array();
#...
if(sizeof($a['somthing_set_later'])>0){
 #...
}
$a['somthing_set_later']="something";

which throws:

sizeof(): Parameter must be an array or an object that implements Countable

To fix this I could initially fill those arrays with null or check for is_countable() first, but I would like to find_and_replace the code over the whole project, which would be easy, if there was another function that doesn't complain.

Is there an alternative function, that wouldn't throw a warning on this code?


Update: optimal would be a built-in function for speed.

rubo77
  • 19,527
  • 31
  • 134
  • 226
  • Why not roll your own e.g. `function mysizeof($var) { return (!isset($var) || !is_array($var)) ? 0 : count($var); }` – Nick Feb 12 '20 at 02:54
  • For clarity, [`sizeof()`](https://www.php.net/manual/en/function.sizeof.php) is an alias of `count()`. As of PHP 7.2 there are no built-in alternative functions that will not emit the warnings, which tends to throw an exception in many popular frameworks. It is advised that you write the application to handle the expected data-types passed to methods and function calls, to avoid unexpected issues. Such as with type hinting/casting. EG: `function(array $var) { return count($var); }` Fixing tends to require a lot of loose code patching, that I myself have had to perform on inherited projects. – Will B. Feb 12 '20 at 05:34

1 Answers1

1

If you want a function that checks sizeof() and ignores uncountable parameters, you could define the following in your project's header:

function countableSizeof($obj) {
  if(!is_countable($obj)) {
    return 0; //or a sentinel value of your choosing
  }
  return sizeof($obj);
}
jbinvnt
  • 498
  • 2
  • 7
  • 16
  • Note: The default value returned by [`sizeof()`](https://www.php.net/manual/en/function.count.php) for any non-array value or object that does not implement `Countable` is `1` and `0` for `null`. So as a direct replacement for `sizeof()`, the current approach will produce different results. – Will B. Feb 12 '20 at 05:45
  • Yes, that is important! So better use the example in the answer of the duplicate: https://stackoverflow.com/a/52444925/1069083 – rubo77 Feb 14 '20 at 08:06