How to cast variable to array

How to cast variable to array

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to cast variable to array

The pattern you are looking at—the if (is_array($v)) check followed by assignment or array pushing—is functionally correct, but it introduces a cognitive load that often isn't worth paying. It forces the developer to manually handle two distinct code paths for a single logical operation: "ensure this is an iterable collection." While this explicit branching works in vanilla PHP, modern tooling and specific frameworks offer more concise syntaxes that reduce boilerplate and potential for error.

The most direct solution in standard PHP relies on the spread operator combined with array wrapping. You can normalize any variable to an array using a ternary operator or a simple conditional expression:

$a = is_array($v) ? $v : [$v];

This approach condenses the logic into a single line without sacrificing readability. It explicitly states the condition (is_array) and the corresponding result, making the intent clear at a glance. However, there is a critical nuance here regarding empty values. If $v is an empty string, [$v] creates an array containing that empty string, whereas an empty string might sometimes be intended to represent "no data" depending on your application logic. Conversely, if $v is already an empty array, the ternary preserves it as an empty array rather than wrapping it in another layer.

In many real-world scenarios, specifically within the Laravel ecosystem, you will encounter a different problem space where this casting is less about normalization and more about converting a string representation of data into an actual array structure. If $v holds a JSON string like {"key": "value"} or ["item1", "item2"], simple type checking won't convert it because the variable is technically a string, not an array. In these cases, you need to parse the content first:

if (is_string($v) && json_validate($v)) {
    $a = json_decode($v, true);
} else {
    // Handle fallback or error
}

Note that json_validate is not a core PHP function; you would typically use json_last_error() checks or rely on framework helpers. The goal here is to ensure you are dealing with structured data before treating it as a collection.

When working with Laravel, the framework often abstracts this away entirely through its Eloquent ORM and collection facades. If your variable $v represents a model relationship or a query result, Laravel's get() method on a relation automatically handles the conversion to a collection (which is essentially an array wrapper).

// If $user has a relationship 'roles'
$roles = $user->roles; // Returns a Collection
$rolesArray = $roles->toArray(); // Explicitly casts to standard PHP array if needed

Using the toArray() method on a Laravel Collection is a deliberate choice. It ensures that subsequent code operates on a plain PHP array, which is useful when passing data to external libraries or APIs that do not understand Eloquent's magic. This explicit conversion avoids unexpected behavior where you might accidentally iterate over a relationship without realizing you are modifying the underlying model state.

There is also the is_null() consideration. If $v can be null, wrapping it as [null] usually isn't desired if null implies "absence of value." In such cases, a ternary that checks for both type and truthiness might be safer:

$a = !empty($v) && is_array($v) ? $v : ($v !== null ? [$v] : []);

This logic ensures you only wrap non-null, non-array values into an array, while explicitly handling the null case to avoid creating a single-element array containing null. This distinction matters when performing subsequent operations like count() or iterating with foreach(), as count([null]) returns 1, which could break downstream logic expecting zero items.

Ultimately, the choice between the verbose if/else block and the concise ternary depends on your team's style guide and the complexity of the surrounding logic. However, sticking to a consistent pattern—whether it's the spread operator syntax in PHP 7+ or Laravel's collection methods—reduces the mental overhead required to parse the codebase. Always remember that "casting" in PHP is rarely automatic; you must explicitly define how a scalar value transforms into a collection context.

Our network