How to Initialize Empty Array in PHP

Initialize An Empty Array in PHP – Code Snippet

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.

initialize empty array in PHP

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.

Php create empty array

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.

get notifications sequence diagram

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.

Conclusion – Initialize empty array in PHP

Wrap Up

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.


Article Categories

Article Tags

© 2022 Confident.Systems