search for in the  
<Pseudo-types used in this documentationVariables>
Last updated: Thu, 19 May 2005

Type Juggling

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.

<?php
$foo
= "0"// $foo is string (ASCII 48)
$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)
?>

If the last two examples above seem odd, see String conversion to numbers.

If you wish to force a variable to be evaluated as a certain type, see the section on Type casting. 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.

Note: The behaviour of an automatic conversion to array is currently undefined.

<?php
$a
= "1";    // $a is a string
$a[0] = "f"// What about string offsets? What happens?
?>

Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being "f", or should "f" become the first character of the string $a?

The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes "f", the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above:

<?php
$a   
= "abc"; // $a is a string
$a{1} = "f"// $a is now "afc"
?>

See the section titled String access by character for more information.

Type Casting

Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.

<?php
$foo
= 10// $foo is an integer
$bar = (boolean) $foo// $bar is a boolean
?>

The casts allowed are:

  • (int), (integer) - cast to integer

  • (bool), (boolean) - cast to boolean

  • (float), (double), (real) - cast to float

  • (string) - cast to string

  • (array) - cast to array

  • (object) - cast to object

Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:

<?php
$foo
= (int) $bar;
$foo = ( int ) $bar;
?>

Note: Instead of casting a variable to string, you can also enclose the variable in double quotes.

<?php
$foo
= 10;            // $foo is an integer
$str = "$foo";        // $str is a string
$fst = (string) $foo; // $fst is also a string

// This prints out that "they are the same"
if ($fst === $str) {
   echo
"they are the same";
}
?>

It may not be obvious exactly what will happen when casting between certain types. For more info, see these sections:



User Contributed Notes
Type Juggling
toma at smartsemantics dot com
09-Mar-2005 08:24
In my much of my coding I have found it necessary to type-cast between objects of different class types.

More specifically, I often want to take information from a database, convert it into the class it was before it was inserted, then have the ability to call its class functions as well.

The following code is much shorter than some of the previous examples and seems to suit my purposes.  It also makes use of some regular expression matching rather than string position, replacing, etc.  It takes an object ($obj) of any type and casts it to an new type ($class_type).  Note that the new class type must exist:

function ClassTypeCast(&$obj,$class_type){
   if(class_exists($class_type,true)){
       $obj = unserialize(preg_replace"/^O:[0-9]+:\"[^\"]+\":/i",
         "O:".strlen($class_type).":\"".$class_type."\":", serialize($obj)));
   }
}
Raja
10-Feb-2005 05:05
Uneven division of an integer variable by another integer variable will result in a float by automatic conversion -- you do not have to cast the variables to floats in order to avoid integer truncation (as you would in C, for example):

$dividend = 2;
$divisor = 3;
$quotient = $dividend/$divisor;
print $quotient; // 0.66666666666667
memandeemail at gmail dot com
09-Dec-2004 07:29
/**
   * @return bool
   * @param array[byreference] $values
   * @desc Convert an array or any value to Escalar Object [not tested in large scale]
   */
   function setobject(&$values) {
       $values = (object) $values;
       foreach ($values as $tkey => $val) {
           if (is_array($val)) {
               setobject($val);
               $values->$tkey = $val;
           }
       }
       return (bool) $values;
   }
tom5025_ at hotmail dot com
24-Aug-2004 03:27
function strhex($string)
{
   $hex="";
   for ($i=0;$i<strlen($string);$i++)
       $hex.=dechex(ord($string[$i]));
   return $hex;
}
function hexstr($hex)
{
   $string="";
   for ($i=0;$i<strlen($hex)-1;$i+=2)
       $string.=chr(hexdec($hex[$i].$hex[$i+1]));
   return $string;
}

to convert hex to str and vice versa
dimo dot vanchev at bianor dot com
10-Mar-2004 09:02
For some reason the code-fix posted by philip_snyder at hotmail dot com [27-Feb-2004 02:08]
didn't work for me neither with long_class_names nor with short_class_names. I'm using PHP v4.3.5 for Linux.
Anyway here's what I wrote to solve the long_named_classes problem:

<?php
function typecast($old_object, $new_classname) {
   if(
class_exists($new_classname)) {
      
$old_serialized_object = serialize($old_object);
      
$old_object_name_length = strlen(get_class($old_object));
      
$subtring_offset = $old_object_name_length + strlen($old_object_name_length) + 6;
      
$new_serialized_object  = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":';
      
$new_serialized_object .= substr($old_serialized_object, $subtring_offset);
       return
unserialize($new_serialized_object);
     } else {
         return
false;
     }
}
?>
philip_snyder at hotmail dot com
27-Feb-2004 09:08
Re: the typecasting between classes post below... fantastic, but slightly flawed. Any class name longer than 9 characters becomes a problem... SO here's a simple fix:

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
   // Example serialized object segment
   // O:5:"field":9:{s:5:...  <--- Class: Field
   $old_serialized_prefix  = "O:".strlen(get_class($old_object));
   $old_serialized_prefix .= ":\"".get_class($old_object)."\":";

   $old_serialized_object = serialize($old_object);
   $new_serialized_object = 'O:'.strlen($new_classname).':"'.$new_classname . '":';
   $new_serialized_object .= substr($old_serialized_object,strlen($old_serialized_prefix));
   return unserialize($new_serialized_object);
  }
  else
   return false;
}

Thanks for the previous code. Set me in the right direction to solving my typecasting problem. ;)
post_at_henribeige_dot_de
03-May-2003 11:37
If you want to do not only typecasting between basic data types but between classes, try this function. It converts any class into another. All variables that equal name in both classes will be copied.

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
   $old_serialized_object = serialize($old_object);
   $new_serialized_object = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":' .
                             substr($old_serialized_object, $old_serialized_object[2] + 7);
   return unserialize($new_serialized_object);
  }
  else
   return false;
}

Example:

class A {
  var $secret;
  function A($secret) {$this->secret = $secret;}
  function output() {echo("Secret class A: " . $this->secret);}
}

class B extends A {
  var $secret;
  function output() {echo("Secret class B: " . strrev($this->secret));}
}

$a = new A("Paranoia");
$b = typecast($a, "B");

$a->output();
$b->output();
echo("Classname \$a: " . get_class($a) . "Classname \$b: " . get_class($b));

Output of the example code above:

Secret class A: Paranoia
Secret class B: aionaraP
Classname $a: a
Classname $b: b
yury at krasu dot ru
27-Nov-2002 03:24
incremental operator ("++") doesn't make type conversion from boolean to int, and if an variable is boolean and equals TRUE than after ++ operation it remains as TRUE, so:

$a = TRUE;
echo ($a++).$a;  // prints "11"
29-Aug-2002 12:26
Printing or echoing a FALSE boolean value or a NULL value results in an empty string:
(string)TRUE //returns "1"
(string)FALSE //returns ""
echo TRUE; //prints "1"
echo FALSE; //prints nothing!
amittai at NOSPAMamittai dot com
21-Aug-2002 01:30
Uneven division of an integer variable by another integer variable will result in a float by automatic conversion -- you do not have to cast the variables to floats in order to avoid integer truncation (as you would in C, for example):

$dividend = 2;
$divisor = 3;
$quotient = $dividend/$divisor;
print $quotient; // 0.66666666666667

Amittai Aviram

<Pseudo-types used in this documentationVariables>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT