Cast arrays to other data type in PHP

Description

The following code shows how to cast arrays to other data type.

Example


/*  w  ww  .jav a 2 s .  c o  m*/
<?php
  $userInfo = array(
    "Name"=>"XML",
    "Location"=>"Main Street, California",
    "Occupation"=>"Programmer",
    "PHP Version"=>5.0);

  //Whether a boolean, integer or double,
  //PHP converts the array to 1
  $asBool = (boolean)$userInfo;
  print("Boolean: $asBool<br>\n");

  $asInt = (integer)$userInfo;
  print("Integer: $asInt<br>\n");

  $asDouble = (double)$userInfo;
  print("Double: $asDouble<br>\n");

  //converting to a string, PHP returns the string "Array"
  $asString = (string)$userInfo;
  print("String: $asString<br>\n");

  //promote an array to a string
  print("Promoted to string:" . $userInfo . "<br>\n");


?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone