- Initialize An Empty Array in PHP Code Example
- Relevant Content: PHP Arrays
- Scenario: Retrieving Notifications in a Social Media Application
- Option1 – Initialize an Empty Array in PHP using Square Brackets
- Option2 – Initialize an Empty Array in PHP using array()
- Using Array as an In-Memory Cache
- How to Initialize empty array in PHP
- Classes and Functions Mentioned
- Want to learn more about PHP?
- Php array create empty array
- Create Empty Array in PHP
- PHP – Create empty array
- Examples
- 1. Create empty array using array()
- 2. Create empty array using square brackets notation
- Conclusion
Initialize An Empty Array in PHP Code Example
We can initialize an empty array using either the square brackets syntax or array(), as follows.
$firstArray = []; $secondArray = array();
The article goes beyond the basics and includes a case study where we use an array to implement an in-memory cache. Curious to know how that works? Stay tuned to learn more.
Relevant Content: PHP Arrays
Arrays are fundamental data structures, no doubt why they form the basis for many other data structures like stacks and queues. Apparently, a fundamental data structure, arrays can be a super helpful component in competitive programming, complex algorithms, or an actual program.
PHP arrays can be categorized as
- Indexed arrays with numeric keys.
- Associative arrays with named keys.
- Multidimensional arrays with sub-arrays.
FuelingPHP has an in-depth article on the types of arrays in PHP.
Scenario: Retrieving Notifications in a Social Media Application
Consider a social media application where you can create a profile and keep in touch with your social circle. Though such an application can be awfully complex, we focus on one important functionality here.
The functionality relates to retrieving notifications for a logged-in user. A naive and inefficient approach would be querying the database every time the user wants to see notifications.
Now that is an okay way, but database calls can be expensive. Users can face delays depending on many factors, including the database server’s geographic location, network traffic, access pattern, and query size.
An efficient solution would be caching the already retrieved notifications into a cache so that the next time user asks for notifications, the request doesn’t have to go all the way to the database and make redundant calls.
The figure above uses some cache-related jargons which are as follows.
- A cache miss is when the data is not available in the cache.
- TTL stands for time-to-live, after which the cache data expires.
We won’t get into other functions related to updating the cache to focus on the in-memory cache and data retrieval. The article includes a sequence diagram and pseudocode for this functionality at the very end.
Option1 – Initialize an Empty Array in PHP using Square Brackets
We can initialize an empty array using square brackets [ ]. The following example initializes an empty array in PHP.
$array = []; //Initializes an empty array
That’s an elegant syntax. We can also add elements to the array using square brackets syntax as follows.
$array[] = "First Element"; print_r($array); /* Array ( [0] => First Element ) */
Similar syntax helps add keys and values to an array.
$array["FirstKey"] = "First Element"; print_r($array); /* Array ( [FirstKey] => First Element ) */
Let’s examine another common method for initializing a PHP empty array.
Option2 – Initialize an Empty Array in PHP using array()
PHP array() is an array initializing function. We call it without arguments for an empty array.
$array = array(); //Initializes an empty array
You can push values to an array using either the square brackets syntax shown previously or array_push().
array_push($array, "First Element"); print_r($array); /* Array ( [0] => First Element )
Cool! We can use either way to initialize an array. I prefer using the square brackets syntax.
Using Array as an In-Memory Cache
There are many production-grade cache solutions available. We intend to express the utility of an array, so we choose to reinvent the wheel and have our own in-memory cache using PHP associative array.
Assuming that a logged-in user request notifications, the following illustration shows the sequence of events.
Let’s realize this in practice through an example.
function fetchNotificationsFromDatabase($user_session_id) < echo "Querying user session data\n"; echo "Fetching notifications for user from database\n"; return "Here are your notifications\n"; >$notifcationsCache = ["Notifications" => []]; function fetchNotificationFromCache($cache) < echo "Fetching notifications for user from cache\n"; if(!empty($cache["Notifications"])) < return $cache["Notifications"]; >return 0; > function notificationEvent($cache) < $notifcationsCache = ["Notifications" =>$cache]; //Initialize cache $notifications = fetchNotificationFromCache($notifcationsCache); //Check cache if(!$notifcations) < $notifcations = fetchNotificationsFromDatabase($_SESSION["user_session_id"]); //Get notifications from database. >return $notifcations; > $GLOBALS["Notifications"][] = notificationEvent($applicationCache["Notifications"]); //Sets cache. print_r($GLOBALS["Notifications"]);
The function names reflect their purpose, and most of the output is console-based – after all, it is just a mock of the feature. The $GLOBALS remain in super scope and accessible everywhere in the running process – not recommended, but a quick workaround for now.
If a user requests notifications the very first time, here’s what the output will be.
/* Querying user session data Fetching notifications for user from database Array ( [0] => Here are your notifications ) */
After the initial request, the results have been cached, and now if the server reruns this script, it is expected to fetch the notifications from the in-memory cache array.
/* Fetching notifications for user from cache Array ( [0] => Here are your notifications ) */
Voila! Arrays are basic but powerful, and that’s just one example. I hope this use case will suffice to reinforce the array’s significance.
How to Initialize empty array in PHP
This article is primarily about exploring the best ways to initialize an empty array in PHP. The article shows two best ways and then extends further by introducing a use case where an array plays a pivotal role in optimizing an application’s performance. It helps in implementing an in-memory cache and helps cut off redundant database calls, which could negatively impact application performance and, thereby, user experience.
I hope you’ve enjoyed this article. Stay tuned for more at FuelingPHP.
Classes and Functions Mentioned
array – (PHP 4, PHP 5, PHP 7, PHP 8) A built-in PHP function for creating an array.
array_push – (PHP 4, PHP 5, PHP 7, PHP 8) A PHP function that pushes one or more elements to the end of an array.
empty – (PHP 4, PHP 5, PHP 7, PHP 8) A core function in PHP that determines if a variable is empty.
Want to learn more about PHP?
We have many fun articles related to PHP. You can explore these to learn more about PHP.
Php array create empty array
// Before php 5.4
$array = array(1,2,3);
// since php 5.4 , short syntax
$array = [1,2,3];
// I recommend using the short syntax if you have php version >= 5.4
Used to creating arrays like this in Perl?
Looks like we need the range() function in PHP:
$array = array_merge (array( ‘All’ ), range ( ‘A’ , ‘Z’ ));
?>
You don’t need to array_merge if it’s just one range:
There is another kind of array (php>= 5.3.0) produced by
$array = new SplFixedArray(5);
Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.
Supposing a large string-keyed array
$arr=[‘string1’=>$data1, ‘string2’=>$data2 etc. ]
when getting the keyed data with
php does *not* have to search through the array comparing each key string to the given key (‘string1’) one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it’s all hidden away.
However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :
Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It’s also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).
When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => 23 ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=0, is_ref=0)int 23
but :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => ’23’ ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=1, is_ref=0)string ’23’ (length=2)
or :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => [1,2], ‘too’ => [1,2] ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
‘too’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
This function makes (assoc.) array creation much easier:
function arr (. $array )< return $array ; >
?>
It allows for short syntax like:
$arr = arr ( x : 1 , y : 2 , z : 3 );
?>
Instead of:
$arr = [ «x» => 1 , «y» => 2 , «z» => 3 ];
// or
$arr2 = array( «x» => 1 , «y» => 2 , «z» => 3 );
?>
Sadly PHP 8.2 doesn’t support this named arguments in the «array» function/language construct.
Create Empty Array in PHP
In this tutorial, you shall learn how to create an empty array in PHP using array() function, with the help of example programs.
PHP – Create empty array
To create an empty array in PHP, we can use array() function or square bracket notation.
Call array() function and pass no arguments to it. The function returns an empty array.
Or given empty square brackets with no elements mentioned between them. The expression represents an empty array
Examples
1. Create empty array using array()
In this example, we create an empty array using array() function and assign it to arr .
To verify if array is empty, we shall print the length of array. An empty array must have a length of zero.
PHP Program
2. Create empty array using square brackets notation
In this example, we create an empty array using square brackets notation and assign it to arr .
PHP Program
Conclusion
In this PHP Tutorial, we learned how to create an empty array using array() function or square bracket notation.