Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast variable to array

I have a variable $v that can be either single string or array of strings
and I have a code:

$a = array(); if (is_array($v)) {     $a = $v; } else {     $a[] = $v; } 

How it can be done in more elegant way? (in other words, how to cast a variable to array)

like image 545
tsds Avatar asked May 11 '11 20:05

tsds


People also ask

Can we use variable in array?

Any variable may be used as an array. There is no maximum limit to the size of an array, nor any requirement that member variables be indexed or assigned contiguously. Arrays are zero-based: the first element is indexed with the number 0.


2 Answers

You can cast a variable to an array by using:

    $var = (array)$arr; 
like image 84
cbroughton Avatar answered Oct 04 '22 15:10

cbroughton


$a = (array) $v; 

is the answer.

like image 28
Kelly Avatar answered Oct 04 '22 17:10

Kelly