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"
*/