Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a PHP array: check for index first?

If I'm deep in a nest of loops I'm wondering which of these is more efficient:

if (!isset($array[$key])) $array[$key] = $val;

or

$array[$key] = $val;

The second form is much more desirable as far as readable code goes. In reality the names are longer and the array is multidimensional. So the first form ends up looking pretty gnarly in my program.

But I'm wondering if the second form might be slower. Since the code is in one of the most frequently-executed functions in the program, I'd like to use the faster form.

Generally speaking this code will execute many times with the same value of "$key". So in most cases $array[$key] will already be set, and the isset() will return FALSE.

To clarify for those who fear that I'm treating non-identical code as if it were identical: as far as this part of the program is concerned, $val is a constant. It isn't known until run-time, but it's set earlier in the program and doesn't change here. So both forms produce the same result. And this is the most convenient place to get at $val.

like image 434
Ben Dunlap Avatar asked Oct 03 '08 20:10

Ben Dunlap


People also ask

How do I check if an array is index PHP?

The array_key_exists() is an inbuilt function of PHP that is used to check whether a specific key or index is present inside an array or not. The function returns true if the specified key is found in the array otherwise returns false.

How do I find the first key of an array?

Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info. You can use reset and key : reset($array); $first_key = key($array);

Does PHP array start at 0 or 1?

To create an array in PHP, we use the array function array( ) . By default, an array of any variable starts with the 0 index. So whenever you want to call the first value of an array you start with 0 then the next is 1 ...and so on. There are different types of arrays in PHP.


1 Answers

For an array you actually want: array_key_exists($key, $array) instead of isset($array[$key]).

like image 83
Zan Lynx Avatar answered Sep 24 '22 02:09

Zan Lynx