Ulterior
Ulterior

Reputation: 2892

php casting variable to array

I am dealing with very strange issue of dealing with garbage in iterating through variable which has been cast to an array

$arr = (array)$var; // problem
$arr = array($var); // ok

The first method seems to work fine on values with integers, but not with strings. Is there any documented difference and does php have real casting ?


The problem is with lavarel 4, Database sources, function on line 704

Upvotes: 0

Views: 139

Answers (2)

georg
georg

Reputation: 214949

If $var is a scalar, it's documented that both lines do the same:

For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

http://www.php.net/manual/en/language.types.array.php#language.types.array.casting

Upvotes: 1

tharindu_DG
tharindu_DG

Reputation: 9261

There are two ways to cast a variable in PHP as a specific type.

  1. using the settype() function
  2. using (int) (bool) (float) etc

More Info : http://www.electrictoolbox.com/type-casting-php/

Upvotes: 0

Related Questions