Jeffrey Roosendaal
Jeffrey Roosendaal

Reputation: 7157

Can someone explain this php type-juggling?

I tried if the following piece of code worked, and it did:

// Lets create and fill a new array
$variable[] = 'value 1';
$variable[] = 'value 2';
$variable[] = 'value 3';

// Implode it, and save it to a a string
$variable   = 'values: ' . implode(', ', $variable);

How come it's able to store the string in $variable, when it's still an array?

I think this is what happens: It creates the new value (and thus it's new data-type) in the memory, and then saves it to $variable, and which point it has to be converted into a string.

Am I right? Wrong? Can someone explain what happens 'behind the scenes' here?

Upvotes: 1

Views: 1481

Answers (1)

Amal Murali
Amal Murali

Reputation: 76656

PHP is a loosely typed language, so it doesn't really care what type a variable is in. When you push new elements using the [] syntax, $variable automatically becomes an array. After the first three statements, $variable will be a single-dimensional array holding three values, namely value 1, value 2 and value 3.

Then, in the next statement, you're storing the imploded result in a string. I guess you got confused because of the same variable name. Here, it's important to note that implode(', ', $variable) is what's evaluated first. The result is a string, which is then concatenated with the string values: and then stored back in $variable (overwriting the array which was there previously).

Here's what happens:

// $variable isn't defined at this point (yet)
$variable[] = 'value 1';
$variable[] = 'value 2';
$variable[] = 'value 3';

/*
print_r($variable);
Array
(
    [0] => value 1
    [1] => value 2
    [2] => value 3
)
*/

$imploded = implode(', ', $variable);
/*
var_dump($imploded);
string(25) "value 1, value 2, value 3"
*/    

$variable   = 'values: ' . $imploded;
/*
var_dump($variable);
string(33) "values: value 1, value 2, value 3"
*/

Upvotes: 2

Related Questions