Laravel 5: Ensuring a Value is an Array With wrap

April 11, 2018 —John Koster

At some point in your PHP adventures, you have either seen, or written code like the following:

1function checkDomains($domains) {
2 if (!is_array($domains)) {
3 $domains = (array)$domains;
4 }
5 
6 foreach ($domains as $domain) {
7 // Perform some operation on the domains array.
8 }
9}

The wrap method allows you to accomplish the same task with much cleaner, and clearer syntax.

#Signature

The signature of the wrap method is:

1public static function wrap(
2 $value
3);

#Example Use

In the introduction of this section, we saw this example code:

1function checkDomains($domains) {
2 if (!is_array($domains)) {
3 $domains = (array)$domains;
4 }
5 
6 foreach ($domains as $domain) {
7 // Perform some operation on the domains array.
8 }
9}

We could do the same thing using the wrap method like so:

1use Illuminate\Support\Arr;
2 
3function checkDomains($domains) {
4 $domains = Arr::wrap($domains);
5 
6 foreach ($domains as $domain) {
7 // Perform some operation on the domains array.
8 }
9}

The Arr::wrap method will not do anything to the input $value if it is already an array.

We can round this section out by implementing a version of checkDomains that will return an array of the domains or URLs and their response times. This example implementation relies on the Guzzle library; if you'd like to test this function or use it, you will need to add the Guzzle library to your project.

1use Illuminate\Support\Arr;
2 
3function checkDomains($domains) {
4 // Ensure that $domains is an array.
5 $domains = Arr::wrap($domains);
6 
7 // An array to hold our response times.
8 $responseTimes = [];
9 
10 foreach ($domains as $domain) {
11 $startTime = microtime(true);
12 // Perform a GET request with the Guzzle HTTP client.
13 with(new GuzzleHttp\Client)->get($domain);
14 $endTime = microtime(true);
15 
16 // Get the response time in milliseconds.
17 $responseTime = floor(($endTime - $startTime) * 1000);
18 
19 // Add the response time to our results array.
20 $responseTimes[$domain] = $responseTime;
21 }
22 
23 return $responseTimes;
24}

We can use this new checkDomains function like so:

1$responseTimes = checkDomains('https://stillat.com/');

At the time of writing, the checkDomains function returned the following results:

1array: [
2 "https://stillat.com" => 665.0
3]

#Global array_wrap Helper Function

The array_wrap helper function is a shortcut to calling Arr:wrap. This function is declared in the global namespace.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.