0

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

11
  • Can you say what $var's value for two example? Commented Jun 24, 2014 at 6:25
  • 3
    The second thing is not typecasting, you are creating an one element array, and the element's value is $var. Commented Jun 24, 2014 at 6:26
  • This is a PHP bug - fixed in PHP 5.2.7 and higher. What version do you use? Commented Jun 24, 2014 at 6:31
  • 2
    Your problem cannot be repoduced: ideone.com/cnkOqV Commented Jun 24, 2014 at 6:33
  • 1
    A first step to provide more information could be to tell us what garbage is. And what the input value is that provides this garbage. Commented Jun 24, 2014 at 6:43

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

so that means thats a bug, I would expect this functionality
@Ulterior: yes, if you've got a reproducible error case, feel free to file it at bugs.php.net. Both lines must do the same.
0

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/

1 Comment

settype results in same garbage on iterating through an array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.