Friday, September 20, 2024

Variables in PHP

This is part 1 in a series of articles.

Variables

A variable is an area of memory which is set aside to store information. This is assigned an identifier by the programmer . You can recognise variables in PHP because they are prefixed with the dollar ( $ ) sign . To assign a variable you use the assignment operator ( = ) . Here is an example of this.

$name = "shedboy";
$intDaysInWeek = 7;

In the first example the variable identifier is $name and the string value “iain hendry” has been assigned to it . In the second example the variable identifier is $intDaysInWeek and the number 7 is assigned to it . Note that in the number example we do not surround the variable with quotes in this way. PHP treats this as a numeric value but if we had put quotes around it then PHP would have treated it as a string.

Variable Naming

There are some guidelines to follow for naming variables in PHP and these are as follows .

1. All variable names must begin with a letter or underscore character .

2 . The name of the variable can be made up of numbers , letters , underscores but you can’t use charcters like + , – , & , , * , etc.

One important thing to note if you are coming from another programming language i that there is no size limit for variables .

Case Sensitivity

One thing that causes many hours of hair pulling and anguish is case sensitivity , PHP is case sensitive (some languages are not) . Here is an example of what I mean.

<<?php
$myname = "shedboy";
echo $Myname";
?>>

Now we all know what we want to do: declare a variable , assign it the value of “shedboy” and then print this on the screen but in this example we have mis-spelled the variable name. When run, the following error is displayed on the screen.

Warning: Undefined variable: Myname in D:\testsample.php on line 3

Example

Using your favourite HTML editor enter the following:

?php
$url = "http://www.programmershelp.co.uk";
$rank = 1;
echo "Our favourite site is ".$url;
echo "
";
echo "It is numbered ".$rank;
?

Here is the output you should get:

Our favourite site is http://www.programmershelp.co.uk
It is number 1

Owner and founder of Programmers help and maxidirectory to name just a few of the many sites.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

Adopting a sales compensation management software can help you with commission management, including compliance reports. That’s what a fractional chief digital marketing officer does !. Final grade calculator.