Home » PHP

PHP Chapter 1 – Variables and Operators

6 November 2009 by Keshav Shetty 5,696 views One Comment

In web development using PHP, it is normal practice to include php codes into html using special tag “<?php” e.g:

<html>

<head></head>

<body>

<?php echo ‘Wlecome to php’; ?>

</body>

</html>

When this file is requested by the browser an web aware server recognizes “<?php” tag and understands that it needs to be interpreted by php, so it will pass it to php interprester,

php interpretor will execute and translates all php code and generates resuting html back to web server. Web server will combine the static html and php interprested html and serves the client.

So you might have understood that we can embed all dynamic contents using <?php tag inside a html code. You might have observed everything is processed at server side and only resulting html is served to the browser, in this sence php is more secured and superior to other scripting language like javascript which is a client side scripting.

Note the following during your development

  1. All php code blocks should start with special php tag i.e “<?php” and ends with ?>
  2. Everyline of php should terminate with ; (Optional for last line of php block)
  3. Php supports escape characters so that interprester will not intefere in the output. e.g: You want to display a new line between two lines then you can use \n i.e <?php echo “first line \n second line”; ?>
  4. There are other escape character like \t (for tab), \r (carriage return), \’ (single quatation mark), \” (double quatation mark), \\ (a backspace)
  5. <? php echo ‘test line’; ?> and <?php echo “test line”; ?> both are same, however when there is a escape character then you need to use “(double quote)

Variable and operator (For more details refer php.net dicument)

Lets start with basic feature of php i.e Variable and operator (almost any language)

A php variable should start with $ symbol and must begin with letter or underscore. e.g: $var1, $_number are valid variables. (php variables are case sensitive)

Inside a html code you can use variable as below

<?php

$name = ‘Keshav’;

?>

<h2>Good work <?php echo $name; ?></h2>

This will out put “Good work Keshav” in your browser.

Another example below to demonstrate numerical values in variables.

Lets add two numbers 2 and 3

<?php

$number1 = 2;

$number2 = 3;

$result = $number1 + $number2;

?>

<h2>Result is <?php echo $result; ?></h2>

or previous line can be replaced with

<h2><?php echo “Result is $result”; ?></h2> (i.e you can use variables inside ” (double quotes)

Below example demonstrate about dynamic variable names use i.e variable name itself is a variable.

<?php

$anAttribute = ‘rate’;

${$anAttribute} = 20;

echo $rate;

?>

To remove (destroy) the variable use unset function call

e.g: <?php

$name = ‘Keshav’;

?>

<h2>First time printing name <?php echo $name; ?></h2>

<?php unset($name) ; ?>

<h2>After unset() printing name <?php echo $name; ?></h2>

The second line should generate an error, because after unset variable no more exist and available for use inside php code.

You can use null as assign value to a variable e.g: <?php $name = null; ?>

To inspect the conetent of variable use var_dump() function, e.g:

<?php

$name = ‘Keshav’;

$price = 30;

var_dump($name);

var_dump($price);

?>

Alternatively you can use print_r() function to achive the same, but with less information.

php variable types (For detailed info refer php.net site)

<?php

// Boolean type (takes only true or false)

$isValidData = true;

// Integer

$length = 15;

// Floating point

$temperature = 98.6;

// string

$name = ‘Keshav’;

// null or empty

$nullDemo = null;

?>

Assigining numerical varibles in other base or notation

<?php

// 9, specified as octal value

$anOctalVariable = 011;

// 1500, specified as hexadecimal value

$anHexVariable = 0x5dc;

// 780, in scientific power notation

$powerVariable = 7.8E+2;

?>

Changing variable data type

Unlike other programming language php supports dynamic chnage in data type during runtime, i.e

<?php

// aVariable is defined as string variable

$aVariable = ‘Keshav’;

// Result is : ‘string’

echo gettype($aVariable);

// Assigning new integer value to aVariable

$aVariable = 100.20;

// Result is : ‘double’

echo gettype($whoami);

?>

As you might have observed PHP’s gettype() operator can be used to identify the data type of variable it is holding.

Casting variable data from one type to other (For more details refer php.net document)

<?php

// Define floating-point variable

$rate = 151.79;

// Cast to Integer

$newRate = (integer) $rate;

// Result: 151

echo $newRate;

?>

Following functions can be used to check the datatype (Function name are self explanatory)

is_bool()
is_numeric()
is_int()
is_float()
is_string()
is_null()
is_array()
is_object()

An integer can hold 2147483647 as the biggest number (Check PHP_INT_MAX)

Constants in php

In php you can define constants as below (The values assigned to constants will remain constants thruout the program)

<?php

define (‘PRODUCT’, ‘Apple’);

define (‘RATE’, 21.6);

echo ‘Fruit ‘ . PRODUCT . ‘ costs ‘ . RATE . ‘ per piece’;

?>

Preferably use all letter as capital to identify constants (Not mandatory)

Airthmatic operations on php variables

php supports +(add), -(subtract), *(multiply), / (division), % (modulus or reminder) operations on variables. Following example is self explanatory

<?php

$a = 12;

$b = 6;

$c = 5;

// addition

$sum = $a + $b;

echo “$a + $b = $sum\n”;

// subtract

$difference = $a – $b;

echo “$a – $b = $difference\n”;

// multiply

$product = $a * $b;

echo “$a * $b = $product\n”;

// divide and get quotient

$quotient = $a / $b;

echo “$a / $b = $quotient\n”;

// divide and get reminder

$modulus = $a % $c;

echo “$a % $c = $modulus\n”;

?>

String concatenation

php uses .(period) operator to concate two string values, e.g:

<?php

$firstname =’Keshav’;

$lastname = ‘Shetty’;

$fullname = $firstname . ‘ ‘ . $lastname;

echo $fullname;

?>

Comparing varibales in php (For more details refer php.net document)

php provides following comparison operators

== (Equal to)
!= (Not equal)
> (Greater than)
>= (Greater than or equal to)
< (Less than)
<= (Less than or equal to)
=== (Equal to and of the same data type – Can be used when strict comparing integer and float variable or bool with integer etc)

Logical operators in php

php has following logical operators

&& AND
|| OR
! NOT (Negate)

Additional assignment operator (Refer php.net manuals)

++ Increment by one
— Decrement by one
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign quotient
%= Divide and assign modulus or reminder
.= Concatenate and assign, please note period symbol before equal(Applicable to strings)

Retriving form values in submit page thru $_POST container.

Following example demostrates the use of retriving values from input.php to result.php

input.php

<html>
<head><title /></head>
<body>
<h2>Eneter your age</h2>
<form method=”post” action=”result.php”>
Age: <br />
<input type=”text” name=”ageBox” /> <p />
<input type=”submit” />
</form>
</body>
</html>

result.php

<html>
<head><title /></head>
<body>
<?php $userAge = $_POST[‘ageBox’]; ?>

<h2>Your are <?php echo $userAge; ?> years old</h2>

</body>
</html>

The form data of Html forms submitted as get can be retrieved thru $_GET container. (For more details refer php.net manuals)

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

One Comment »

  • agen sabung ayam said:

    I am not suгe the pⅼace you are getting yօur іnformation, Һowever goߋd topic.
    Ι must spend some time studying mߋre or understanding morе.
    Thank you for magnificent informatіon I used to be in search ⲟf thiѕ info fоr
    mү mission.

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.