Dumb Question Dumb Question - 1 month ago 6
PHP Question

Performance: is_numeric() and is_string() in a foreach loop

I have a bunch of arrays in an array ex.

$array =
array(
array(/../),
array(/../),
array(/../),
//upto 100-200 arrays
);


After that, I will use
foreach
to
echo
all of them. There is some checking here whether the
$key
is
is_numeric()
or
is_string()
, for example:

array(
'the_key_here_is_numeric',
'string' => 'the key is string'
);


So I have a
foreach
like this:

foreach($array as $arr => $arrays) {
foreach($arrays as $key => $value) {
if(is_numeric($key)) {
/.../
}
if(is_string($key)) {
/../
}
}
echo /../;
}


When I tested this using
KCacheGrind
, obviously the
is_string()
and
is_numeric()
will be used multiple times, my question is, will this affect the performance? If so, is there a better way to do this?

Answer

Just use else. Then condition will be check only once

Not

if(is_numeric($key)) {
         /.../
      }
      if(is_string($key)) {
         /../
      }

But

  if(is_string($key)) {
     /../
  } else {
     /.../
  }