40 of 410 menu

The arrayval Function

The standard PHP library does not have an arrayval function, but you can implement similar functionality yourself. Below is an example implementation that converts any value to an array: if the value is already an array, it is returned unchanged; for other types, an array with one element is created.

Function Implementation

<?php function arrayval($value): array { return is_array($value) ? $value : [$value]; } ?>

Usage Example

Let's convert a string to an array using our function:

<?php function arrayval($value): array { return is_array($value) ? $value : [$value]; } $res = arrayval('abcde'); print_r($res); ?>

Code execution result:

['abcde']

Usage Example

Let's try to convert a number:

<?php function arrayval($value): array { return is_array($value) ? $value : [$value]; } $res = arrayval(123); print_r($res); ?>

Code execution result:

[123]

Usage Example

Let's check the work with an array:

<?php function arrayval($value): array { return is_array($value) ? $value : [$value]; } $res = arrayval([1, 2, 3]); print_r($res); ?>

Code execution result:

[1, 2, 3]

Alternative Solutions

PHP has other ways to convert to an array:

<?php // Using (array) type casting $array = (array)'string'; print_r($array); // ['string'] // For objects, type casting works differently $obj = new stdClass(); $obj->prop = 'value'; $array = (array)$obj; print_r($array); // ['prop' => 'value'] ?>

See Also

  • the is_array function,
    which checks if a variable is an array
  • the settype function,
    which converts the type of a variable
byenru