Insert into VS is_array () array

Does anyone know of any problems, performance, or other features that might arise when moving a variable into an array, instead checking it first?

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

OR

$v = '1';

instead:

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

I started using:

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

It stops code repetition quite a bit - but performance in my opinion, not ugly code.

Also, does anyone know how php processes an array array? There are no errors, but does the php server check the array array and then return the result before performing the casting process?

+5
source share
3 answers

-: - . !

, ,

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

, ( , )

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

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

, , . , "" .

: , .

+7

, , , . , , 1000000 :

check first: 2.244537115097s
just cast:   1.9428250789642s

()

( in_array) () .

+2

Another option here (this can also be done inline, of course, to avoid calling the function):

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

This seems a little faster than is_array, but your mileage may vary.

The problem with casting into such an array (which is also an option)

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

This is faster than is_array for small arrays, but catastrophically slower for large ones.

+2
source

All Articles