Another useful feature is accessing your custom object collections as arrays in PHP. There are two interfaces available in PHP (>=5.0.0) core to support this: ArrayAccess and Iterator. The former allows you to access your custom objects as array.
Assume we have a user class and a database table storing all the users. We would like to create a UserCollection class that will:
allow us to address certain user by their username unique identifier
perform basic (not all CRUD, but at least Create, Retrieve and Delete) operations on our users collection
Consider the following source (hereinafter we're using short array creation syntax  available since version 5.4):
then we can :
which will output the following, assuming there was no testuser before we launched the code:
IMPORTANT:offsetExists is not called when you check existence of a key with array_key_exists function. So the following code will output false twice:
Let's extend our class from above with a few functions from Iterator interface to allow iterating over it with foreach and while.
First, we need to add a property holding our current index of iterator, let's add it to the class properties as $_position:
Second, let's add Iterator interface to the list of interfaces being implemented by our class:
then add the required by the interface functions themselves:
So all in all here is complete source of the class implementing both interfaces. Note that this example is not perfect, because the IDs in the database may not be sequential, but this was written just to give you the main idea: you can address your objects collections in any possible way by implementing ArrayAccess and Iterator interfaces:
Note that isset() treats a null valued element as non-existent. Whereas !empty() does the same for any element that equals false (using a weak comparision; for example, null, '' and 0 are all treated as false by !empty()). While isset($map['foobar']); is true, !empty($map['foobar']) is false. This can lead to mistakes (for example, it is easy to forget that the string '0' is treated as false) so use of !empty() is often frowned upon.
Note also that isset() and !empty() will work (and return false) if $map is not defined at all. This makes them somewhat error-prone to use:
You can also check for ordinal arrays:
Note that isset() has better performance than array_key_exists() as the latter is a function and the former a language construct.
You can also use key_exists(), which is an alias for array_key_exists().
Checking if a value exists in array
The function in_array() returns true if an item exists in an array.
You can also use the function array_search() to get the key of a specific item in an array.
In PHP 5.5 and later you can use array_column() in conjunction with array_search().
This method is often used in frameworks to pass an array of variables between two components.
Initializing an Array
An array can be initialized empty:
An array can be initialized and preset with values:
An array can also be initialized with custom indexes (also called an associative array):
If the variable hasn't been used before, PHP will create it automatically. While convenient, this might make the code harder to read:
The index will usually continue where you left off. PHP will try to use numeric strings as integers:
To initialize an array with fixed size you can use SplFixedArray:
Note: An array created using SplFixedArray has a reduced memory footprint for large sets of data, but the keys must be integers.
To initialize an array with a dynamic size but with n non empty elements (e.g. a placeholder) you can use a loop as follows:
If all your placeholders are the same then you can also create it using the function array_fill():
array array_fill ( int $start_index , int $num , mixed $value )
This creates and returns an array with num entries of value, keys starting at start_index.
Note: If the start_index is negative it will start with the negative index and continue from 0 for the following elements.
Conclusion: With array_fill() you are more limited for what you can actually do. The loop is more flexible and opens you a wider range of opportunities.
Whenever you want an array filled with a range of numbers (e.g. 1-4) you could either append every single element to an array or use the range() function:
array range ( mixed $start , mixed $end [, number $step = 1 ] )
This function creates an array containing a range of elements. The first two parameters are required, where they set the start and end points of the (inclusive) range. The third parameter is optional and defines the size of the steps being taken. Creating a range from 0 to 4 with a stepsize of 1, the resulting array would consist of the following elements: 0, 1, 2, 3, and 4. If the step size is increased to 2 (i.e. range(0, 4, 2)) then the resulting array would be: 0, 2, and 4.
range can work with integers, floats, booleans (which become casted to integers), and strings. Caution should be taken, however, when using floats as arguments due to the floating point precision problem.
Validating the array type
The function is_array() returns true if a variable is an array.
You can type hint the array type in a function to enforce a parameter type; passing anything else will result in a fatal error.