logo

What are the PHP data types?

PHP Data Types

Category: PHP

by designzone

2014-10-09 18:39:50

link: Full List of PHP Data types

boolean

$school_is_out=true; //assign a value to a variable

/**
 * Test the variable. If it evaluates to TRUE, print output
 */
if ($school_is_out === true) {
  echo "Go home!\n";
}

Output:
Go home!

string

$degrees=100; // assign an INTEGER value to the degrees variable
$myVariable="cold"; // initialize myVariable and assign a STRING value to it

/**
 * Based on a condition (degrees is more than 79), change the value of the variable
 */
if ($degrees > 79) {
  $myVariable="hot";
}
echo "The weather is very " . $myVariable . " today.\n"; // print new value

Output:
The weather is very hot today. 

array
There are many types of arrays. This is a simple numeric array example

$some_string="Chevy"; //assign a random value to a variable

/**
 * A string can be though of as an array of characters, starting at position zero.
 * So, C is at position zero, h is at position 1, e is at position 2, and so on.
 * Here is how you would retrieve those individual values from an array.
 */
$give_me_a_c = $some_string[0];
$give_me_a_v = $some_string[3];
echo "PRINT \"Cv\": " . $give_me_a_c . $give_me_a_v . "<br>\n";
// although the string is 5 characters long, the array is from 0-4,
//so position 5 is blank
$give_me_a_blank = $some_string[5]; 
echo "PRINT \"BLANK\": " . $give_me_a_blank . "<br>\n";

Output:
PRINT "Cv": Cv
PRINT "BLANK":

integer
/**
 * Simple integer example: 123
 * When you assign an int to a variable, you do not use quotes!
 */
$myNum = 2; //this is an integer
$myNumAsString = "2"; //this is NOT an integer. It is a string

$newNumber = ($myNum + 2);     
echo "New Number: " . $newNumber . "<br>\n";

Output:
New Number: 4

object
/**
 * The dog class
 */
class dog {

  public $name;

  public function __construct( $name ) {
    $this->name = $name;
  }

  public function get_name() {

    return $this->name;

  }

}

//create a new object and give your dog a name
$doggy = new dog("Max");

//Get your dog's name and store it in a variable
$theDogsName = $doggy->get_name();     

//Print out the variable
echo "The dog's name is " . $theDogsName . "<br>\n";

//get the type of our new object
$whatIsTheType = gettype($doggy);

//show the type
echo "The type of doggy is an: " . $whatIsTheType . "<br>\n";
?>

Output:
The dog's name is Max
The type of doggy is an: object

comments powered by Disqus