开发者

Cast to array VS is_array()

Does anyone know of any issues, performance or other, that can occur by casting a variable to an array instead checking it first?

// $v could be a array or string
$v = array('1','2','3'); 

OR

$v = '1';

instead of:

if (is_array($v)) foreach ($v as $value) {/* do this */} else {/* do this */}

I've started to use:

foreach((array) $v as $value) {
    // do this
}

It stops the repetition of code quite a bit - but performance is on my mind, not ugly code.

Also, does anyone know how php handles casting an array to an array? No errors are thrown but does the php engine check if it's a开发者_StackOverflow社区 array, then return a result before doing the cast process?


First: Premature optimization is the root of all evil. Never let performance influence your coding style!

Casting to an array allows to some nice tricks, when you need an array, but want to allow a single value

$a = (array) "value"; // => array("value")

Note, that this may lead to some unwanted (or wanted, but different) behaviours

$a = new stdClass;
$a->foo = 'bar';
$a = (array) $a; // => array("foo" => "bar");

However, this one

if(is_array($v)) {
  foreach($v as $whatever) 
  {
    /* .. */
  }
} else {
  /* .. */
}

allows you to decide what should happen for every single type, that can occur. This isn't possible, if you cast it "blindly" to an array.

In short: Just choose the one, that better fits the needs of the situation.


As Felix Kling says above, the best solution is to have your data come from a source that guarantees its type. However, if you can't do that, here's a comparison for 1000000 iterations:

check first: 2.244537115097s
just cast:   1.9428250789642s

(source)

Just casting without checking (using in_array) seems to be (slightly) quicker.


Another option here is this (this can be done inline as well, of course, to avoid the function call):

function is_array($array) {
      return ($array."" === "Array");
}

This seems to be slightly faster than is_array, but your mileage may vary.

The problem with casting to an array like this (which is also an option)

if ((array) $v === $v)

Is that it's faster than is_array for small arrays, but disastrously slower for large ones.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜