cramerz logo

Php Variables


A variable is like a temporary box in computer's memory to store data. PHP uses Variable to store different type of Data.

For example, if we want to store our name in a PHP program and then want to see it on the web page, we can use PHP variable to store our name.

In PHP language we use dollar sign ($) to declare a variable. A value can be assigned to variable using equal sign (=). If vale is numeric, then we can simply type it otherwise, if its string (words, messages) then we use double quote ("") to write value.

PHP Variable Example

In the example below, a variable named “var” is declared and text value is assigned to it. echo command can be used for displaying the value of Variables.


<?php

$var = "this is my variable. I am storing it in memory";

echo $var;

?>

 

PHP isset()

isset() is a PHP construct and can be used to check if a variable exists.

Example of isset()


<?php

$myvar = "some value";

if(isset($myvar))
{

  echo $myvar;

}

?>

 The above example first declares a variable $myvar and then

Variables and Strings

Unlike Java, variables in PHP do not have a strict type and do not need to be declared before they are used, that's why php is loosely typed language. Variables names are preceded by a dollar sign, and must always start with a letter or underscore. They are case sensitive, and may contain any number of letters and digits after the first character.


While variables do not have specific types, PHP still maintains the concept of a type. The four principle types in PHP are:

PHP also has support for resources, which we will cover when we discuss mySQL, and objects, which we will not be covering at all.

<?php   echo "<p>Hi there!</p>";   $someString = "<p>Hi again</p>";   echo $someString;   $name = 'Hilda';   // variables can be embedded in double quotes echo "<p>Hello, $name</p>";   // it doesn't work with single quotes echo '<p>Hello, $name</p>';   // Long, multiline strings can be defined using so called HEREDOC syntax:   $string = <<<EOD This string can contain both "double" and 'single' quotes, and any variables such as $name will be interpolated (i.e replaced with their value). The string ends at the first occurence of the sequence of characters specified at the beginning after the <<<, like this: EOD;   $firstString = 'Monkeys '; $secondString = 'like '; $thirdString = 'bananas';   // The . operator adds strings together $fourthString = $firstString.$secondString.$thirdString;   echo "<p>$fourthString</p>";   // Numbers can be used in variables as well   $vat = 1.175; $price = 20; $pricePlusVat = $vat * $price;   echo "<p>An item costing £$price is £$pricePlusVat including VAT.</p>";   ?>



all rights reseverd by Cramerz.com©. web development by web design company DotPeak. hosting by HostBay
all contents on cramerz are the property of Cramerz.com. web design courses