Thursday 11 October 2012

PHP Chapter 2 Variables



Chapter 2 Variables

  •          A variable is a container that’s used to store both numeric and non-numeric info.
  •          Use a dollar ($) symbol in front
  •          Must begin with letter or underscore
  •          No commas question marks, spaces or periods
  •          =  Assign the value to the right side of the equation to the variable on the left
  •          Variable names in PHP are case-sensitive.

Example 1

<?php
$name = 'Janine';
echo "welcome to $name 's Blog";
Example 2

<?php
// assign value to variable
$now = 2012;
// assign variable to another variable
$currentYear = $now;
// perform calculation
$lastYear = $currentYear - 1;
// output: '2011 has ended. Welcome to 2012!'
echo "$lastYear has ended. Welcome to $currentYear!";
?>
Example 3
How to set a variable’s name dynamically


<?php
// set a variable
$attribute = 'oranges';
// create a new variable
// its name comes dynamically
// from the value of $attribute
${$attribute} = 200;
// output: 200
echo $oranges;
?>
Download here: https://docs.google.com/file/d/0B7SlVynBEEAbRGU3NXJteDF5RHc/edit



Destroying Variables

  •   unset() function


Example 4
<?php
$car = 'Porsche';
// output: 'Before destroying, my car is a Porsche'
echo "Before destroying, my car is a $car";
// destroy variable
unset($car);
// print variable value
// this will generate an 'undefined variable' error
// output: 'After destroying, my car is a '
echo "After destroying, my car is a $car";
  •  This will result in an undefined variable error message.
  •   This message may or may not be visible in the output page.
  •   Alternatively, empty a variable of its contents by assigning PHP’s special NULL
  •    $car = NULL;


Var_dump()
    • Used to display structured information (type and value) 
    •  print_r() function  performs  same function as var_dump(),although it returns less information.

Example 5

$number=678;
Echo var_dump($number);
//Output int(678) 

$name="janine";
Echo var_dump($name);
//Output string(6) "janine"


Download here: https://docs.google.com/file/d/0B7SlVynBEEAbTGJ2Z2N1bVJXdzg/edit

Data Types


Boolean
·         1(true) or 0 (false) values

Example
$validAge = true;

 Integer
·         A whole number

Example
$age = 15;

Floating point
·         A number that includes decimal places, such as 5.24 or 123.456789.
·         This is often called a real number or a float.

Example
$temp = 99.6;

String
·         A series of single characters

Example
$cat = 'Garfield';

Null
·         Empty variables
·         variable without any data

Example
$train = null;




PHP support numbers written in hexadecimal, octal, or scientific notation

<?php
// 8, specified as octal value
$a = 010;
// 1500, specified as hexadecimal value
$b = 0x5dc;
// 690, in scientific notation
$c = 6.9E+2;
?>









0 comments on "PHP Chapter 2 Variables"

Post a Comment

 

Janine Keyser J9 Photography