Casting Values to Array

PHPPosted on

Sometimes, instead of type-checking values, we can instantly cast them to types we want. We can save some lines of code by being a bit more clever.

// Instead of this
$value = is_array($value) ? $value : [$value];

array_map(function ($item) {
    //
}, $value);

// You can do this
array_map(function ($item) {
    //
}, (array) $value);

Need a web developer? Maybe we can help, get in touch!

Looking for web dev job?
You can check them on Jooble.

To see and write comments, you must allow the related (Disqus) cookies. For more information, please visit our privacy policy page.

Similar Posts

More content in PHP category