top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is Type Juggling in PHP?

+1 vote
471 views
What is Type Juggling in PHP?
posted Jul 2, 2014 by Rahul Mahajan

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes

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"
*/
answer Jul 3, 2014 by Vrije Mani Upadhyay
0 votes

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.

$foo += 2; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs"; // $foo is integer (15)
Also in case of string conversion to numbers.
If you wish to change the type of a variable, see settype().
If you would like to test any of the examples in this section, you can use the var_dump() function.

answer Jul 4, 2014 by Mohit Sharma
Similar Questions
0 votes

Have two questions -
1. How to find type of a variable in PHP.
2. How to find the type of an array in PHP.

Please help.

...