Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP How to cast variable to array?
To cast a variable to array in PHP, use the array casting syntax. This is useful when you need to ensure a variable is always an array type, regardless of its original data type.
Syntax
The basic syntax for casting to array is ?
$yourNewVariableName = (array)$yourVariableName;
Example with Array Variable
When casting an existing array, it remains unchanged ?
<?php
$nameArray = array('Mike', 'Sam', 'David');
$valueArray = (array)$nameArray;
print_r($valueArray);
?>
Array
(
[0] => Mike
[1] => Sam
[2] => David
)
Example with String Variable
Casting a string to array creates a single−element array ?
<?php
$name = "John";
$nameArray = (array)$name;
print_r($nameArray);
?>
Array
(
[0] => John
)
Example with Integer Variable
Integers are also converted to single−element arrays ?
<?php
$number = 42;
$numberArray = (array)$number;
print_r($numberArray);
?>
Array
(
[0] => 42
)
Conclusion
Array casting in PHP converts any variable type to an array. Existing arrays remain unchanged, while scalar values become single−element arrays with index 0.
Advertisements
