I'm developing a module with some arrays in it. Now my array contains:
$omearray = array (
'#title' = 'title',
0 = array ( 'another array', '2ndvalue', ),
);
foreach($omearray as $key => $value)
When I load the array to display I want to check whether the $key
value is a 0
, 1
, 2
, 3
, etc. or a $key
value that starts with a #
.
Which would be better to use: checking if the value is_int()
or a regex that checks whether the first character is a #
?
EDIT: checking stringpos 1 is #
vs is_int()
since regex seems to be slow.
Since if ($key[0]=='#')
is faster and is_int()
is exhaustive, and ||
is a short circuit operator with left associativity (evaluates from left to right, see example 1 on http://php.net/manual/en/language.operators.logical.php) I would say:
if ($key[0]=='#' || is_int($val)) /* etc */
Because this way you only need to bother about using the # key naming self made convention with the keys you'll compare so much that you'd benefit from an optimization.
But unless you're making a huge number of evaluations I would stick to just if(is_int($val))
, because it's clearer and less messy.
I would go for the is_int()
, because you are not dependent on the string. It can be anything and your code will still just take the integer indeices. Looking for # as the first character will prevent that flexibility. But if you are absolutely sure that the string's first character will always be a #, than the $Key[0] == '#'
will be the fastest option.
I would check it using if($key[0]=="#")
You can also check if the $value is an array (is_array($value)
), in this case you dont need either regex,is_int, and # char.
PS: #
character means (somewhere) "I'm a number/ID"
if (is_int($val) || $val{0} == '#') ...
You haven't given much insight into your actual data or reason for choosing this structure, but depending on that info, altering your structure so that you aren't inter-mixing integer indexes with hash keys may be an option:
$omearray = array(
'#title' => 'title',
'foo' => array(
'anotherarray',
'2ndvalue'
)
);
foreach ($omearray as $key => $value) {
if ($key == 'foo') {
// do something with $value, which is the 2nd array, numerically indexed
}
}
Apologies if this solution doesn't suit your needs.
You can check if string is integer
or if it starts with #
or both
or whatever.
It's all makes not a slightest difference.
It is not a part of your code that may affect any performance issue ever.