Among the most important concepts of the programming is the concept of variable. Like any language, PHP handles data. For a dynamic site, these data are variables. In addition, they may be of different types, such as text string, as you have used the echo statement in the form of whole or decimal numbers or as true or false boolean values (TRUE or FALSE). These basic types are the most used, but there are others who may be compounds types, such as arrays and objects, or specific types, as resource or NULL. . We will see that the variable part of the mechanisms which make a dynamic application. Let’s get into the thick of it.
We’ll be covering the following topics in this tutorial:
What is a variable?
The variables are designed to store data that will be used and may be modified during program execution. PHP, like Perl, uses a particular form of syntax for defining a variable. The variables are shown with a ‘$’ character prefixing the identification of this variable. For example, to declare a new variable name “myVariable”, simply call $myVariable inside source code.
Unlike the language like C, PHP does not require prior notification of identifiers before use. The variables are say untyped, that is to say, a variable may take a value character string and then be used for contain an integer. The type is defined in the allocation of this variable. It is partly this flexibility of use makes PHP simple language and easy to access.
A variable is a primitive type of data structure (integer, real, character, string, boolean or null) or structured type (array or object) that can store one or more values. Each value of a variable is likely to be replaced by another during program execution. Hence the term “variable”. In programming, a variable is defined according to four key information listed below:
• A name
• A type
• A values
• Semantics (meaning) after operations on this variable. More concretely, it is the value of the variable logic from its original context?
Each variable has a unique identifier, which always starts with the character dollar ($) followed by the variable name. The rules for creating variable names are the following :
• The name starts with an alphabetic character, caught in sets [a-z], [A-Z] or the underscore (_).
• The following characters can be the same more numbers.
• The name length is not limited, but it should be reasonable under penalty confusion in code entry. It is advisable to create the variable names more “speaking” as possible. Rereading the code containing the variable $clientname by example, you better know what you work as if you had written $x or $y.
• The variable declaration is not mandatory at the beginning of script. This is a notable difference with strongly typed languages such as Java or C. You can create variables anywhere, provided of course to create them before using them, although it remains possible to call a variable that does not exist without cause error.
• The initialization of variables is not compulsory and an uninitialized variable has no specific type.
• Variable names are case sensitive (uppercase and lowercase). $myvar and $MyVar do not refer to the same variable.
Schematically, a variable can be treated as an opaque box on which is pasted a label with a name (the name of the variable). Inside this package is something (the value) of a specific type (the type of the variable). When we want to get this value, we do not speak directly to it but we will make reference by selecting the box by name.
Take an example more meaningful. A doctor wishes to obtain information regarding the health status of one of his patients (Rajan). To get it, he will ask his secretary to get him the Rajan folder where is this information that he does not know!
Determine the type of a variable
Before handling variables, it may be useful to know their type. This ensures that the result is consistent with what is expected and that there is no incompatibility between the types of these variables. The increment operator applied to a string, for example, can produce curious results.
The main function of determining the type of a value is gettype (), the syntax is:
• string gettype($mavar)
It returns a string containing the type of the variable.
The following functions are used to check whether a variable is a specific type:
• is_integer($VType) or is_int($VType)
• is_double($VType)
• is_string($VType)
• is_bool($VType)
• is_array($VType)
• is_object($VType)
• is_resource($VType)
• is_null($VType)
They return the Boolean value TRUE if the variable is of the desired type from FALSE otherwise.
You can tell if a variable is a scalar value by calling the function is_scalar ($VType) and, specifically, whether it contains a digital value type integer or double by calling the function is_numeric ($VType).
In the following code, the $VType variable is incremented by one only if it contains a numeric value, and the variable $var2 is concatenated with string “all” only if it is of type string:
<?php $VType = 73; if (is_int($VType)) { $VType ++; echo "The variable is $VType <br />"; } // Output: The variable is 74 $VType2 = "Hello"; if (is_string ($VType2)) { $VType2 = "all"; echo $VType2; } // prints "Hello" ?>
Declare and initialize a variable
After this somewhat theoretical introduction, we start the practical part of the subject. This is the declaration and initialization of a variable in PHP. Unlike very typed languages like C, C ++ or Java; PHP does not matter at variable typing. For example, for the same variable, the programmer is free to assign an integer value to a time T1 and then to assign a string to a time T2. They say that PHP is a language typing “weak and dynamic.” This makes its use more flexible by developers but not necessarily more assiduous … This is also something we can blame PHP.
To adopt good practices from the start, we advise you to declare all your variables with a type and assign a default value. Remember the term of assignment to pass.
Furthermore, it is necessary to appoint the variables with meaningful names to facilitate the reading of the code. A misnamed variable will be source of problem during a debugging or maintenance of the program weeks later.
A variable must be declared with the sign $dollars are followed by letters (uppercase or lowercase) or an underscore (_ dash underlined). Below is a summary table of correct and incorrect syntax for variable declaration.
Correct | Incorrect | Explications |
$variable | variable | A variablemust start with$ |
$Variable1 | $Variable 1 | Spaces are not allowed |
$variable_suite | $variable-suite | The dashis prohibited |
$_variable | $-variable | The dashis prohibited |
$variable2 | $2variable | There canbe anynumber after the$ |
Note: PHP is one of the few programming languages accepting accented characters in variable names. However the use is strongly discouraged for reasons of maintenance and portability.
The following script shows the declaration of 6 different types of variables. The first and second are chain-type characters, the third integer, boolean fourth, table type of the fifth and last type of student. We will not address the latter two in this tutorial. Other tutorials are dedicated to the tables and object oriented programming.
Reporting different types of variables
<?php $firstname = 'Rajan'; //Type string (character string) $name = "Sajan"; //Type string (character string) $age = 19; // Integer type $isStudent = true; //Boolean Type $course= array ('physical', 'Chemistry', 'Computer', 'philosophy'); //Type Table $aStudent = new Student (); //Student type object ?>
To declare a variable:
• string: one surrounds the character string in quotes or apostrophes.
• integer, real or floating: we write the value as. For floating, the comma is replaced by a point (writing to the US).
• Boolean: true or false is written directly.
• without the type: if one does not wish typing the variable, it is assigned a null value.
Note: the type of a variable is not explicitly stated as in Java, C or C ++ but implicitly when assigning a value.
Variable names are case-sensitive, which means that the interpreter will make the difference between two variables written differently. For example, $ name and $ NAME will be considered as two completely separate variables.
By convention, variable names consist of several words (example: $ aStudent) must have the first word lowercase and other words with the first letter capitalized. This rule is not necessarily to follow but strongly recommended since it is part of good programming practices.
Note: It is recommended to place the php.ini error_reporting to E_ALL on all your pages in order to trace any errors generated. The misdeclared or uninitialized variables can be a source of analytical error.
The value assignment to a variable
The assignment allows to set a value to a variable. It is by means of the equal symbol =. In PHP, you can assign a variable by value or by reference. In the previous script, we said 6 variables and have them assigned to each one / multiple value (s) by default.
In the following example:
$myvar = expression;
the variable $myvar takes the value of the expression, which can be a numeric value,
example, a literal string, but also another variable or a valid PHP expression containing functions.
The example below shows how to change the value of a variable. Nothing is complicated since it is exactly the same as before.
<?php $firstname = 'Rajan'; $age = 19;
echo $firstname; // Display ‘Rajan’
echo ‘<br/>’;
echo $age; // Display 19
$firstname = ‘Sajan’;
$age = 18;
echo'<br/>’;
echo $firstname; // Display Sajan ‘
echo ‘<br/>’;
echo $age; // Display 18
?>
Explanation: we have two variables initialized $firstname and $age We display value to control. Then we update the variables affecting them each a new value. Finally, we show the new values. We notice when we lost the original values. An assignment so will overwrite the old data with the new.
Concatenation, what is it?
This term somewhat “primitive” lies a fundamental principle related variables. Concatenation is neither more nor less than the operation for joining two or more data in a variable. This operation is performed using the concatenation operator which is the period (.). Let’s illustrate this with an example:
Concatenation
<?php // Variable Declaration $firstname = 'Rajan'; $lastname = 'Singh'; $identity = ''; // We concatenate $ name and $ firstname in $identity $identity = $firstname ." " . $lastname; // Display Rajan Singh echo $identity; ?>
We placed here in $identity, the content of variable $firstname followed by a space and then by concatenating the contents of the variable $lastname.
We could have also proceed in the following manner, which prevents us to use a new $identity.
Another example of concatenation
<?php // Variable Declaration $firstname = 'Rajan'; $lastname = 'Singh'; // We concatenate $firstname and $lastname $firstname .= ' '. $lastname; // Display Rajan Singh echo $firstname; ?>
The above concatenation syntax means that there is added space and content of the variable $lastname after the contents of the variable $firstname. Thus, the syntax is similar to the following:
Mathematical operations on variables
Variables can contain numbers. It is therefore logical that we can mathematically operate on these values. PHP offers a series of mathematical operators ensuring that. It is therefore possible to add, divide, multiply or subtract the values of variables.
The examples below illustrate the use of these different mathematical operators.
Mathematical operations on variables
<?php // Declare the variables mathematics $a = 10; $b = 2; $c = 0; // $c is 10 + 2 = 12 $c = $a + $b; // $c is 10 x 2 = 20 $c = $a * $b; // $c is 10/2 = 5 $c = $a / $b; // $c is 10 - 2 = 8 $c = $a - $b; // $c is the remainder of the division by $b $a is 0 $c = $a % $b; // Increment $a $a++; // Decrements $b $b--; ?>
The modules operator (%) returns the remainder of dividing two numbers.
The increment operator increases by 1 the value of the variable. The $a++ syntax is identical to a + = $1 and $a = $a + 1.
The decrement operator decreases by 1 the value of the variable. Syntax $b– is identical to b -= $1 and $b = $b-1.
Dynamic variables
They appeared with version 4 of PHP and also called “dynamic variable”. Dynamic variables are variables whose name depends on other variables. The names of these variables are dynamically built during the execution of PHP code. Let’s take an example:
Using dynamic variables
<?php // Variable definitions $doll = 25; $car = 17; $console = 250; // Choosing a toy $toy = 'console'; // Display the selected toy prices echo $toy, ' : ', $ $toy, '€'; // Returns 'console: 250 €' ?>
In this example, we declare three variables that represent the price of 3 toys (a doll, a car and a video game console). Then we declare a variable $toy in which to store the name of the toy for which it is desired to know the price. Here we decided to know the price is the video console. Finally, through an echo () statement, it displays the selected toy (video game) and its price by making a variable variable. So $toy = ‘console’ but $toy is similar to $console. Indeed, the value of $toy has become the name of the variable.
Test of the existence of a variable
In a program, it is often useful to know whether a variable exists before you can use it. PHP provides developers the function (structure of language) isset () that indicates whether or not the passed in variable exists. This function returns a boolean TRUE or FALSE. Let’s illustrate this with an example:
Existence test variables in a program
<?php // Variable Declaration $firstname = 'Rajan';
echo isset ($firstname); // Return TRUE -> shows 1
echo ‘<br/>’;
echo isset ($lastname); // Return FALSE -> displays nothing
?>
In our example, $firstname is declared so isset() returns TRUE. As for the $lastname variable, it is not declared in the program so isset() returns FALSE.
Note: We recommend instead using the empty() that indicates whether a variable is empty or not. Therefore making this test, it allows to know two things:
• The variable exists or not (it is declared)
• The variable contains a value or is empty (null for example)
Destruction of a variable
It is also sometimes useful to destroy variables that clutter the program that no longer serve. By default, all variables are deleted automatically at the end of program execution, but it is nevertheless possible to force their removal running. To do this, PHP has the function (or rather the language structure) unset() that takes a parameter variable to remove.
Deleting one or more variables
<?php // Variable Declaration $firstname = 'Rajan'; $lastame = 'Singh'; $age = 19; $aStudent = true; // Deleting a variable unset ($firstname); // Delete multiple variables unset ($lastname, $age, $aStudent); ?>
Note: If you want to delete multiple variables at once, simply to inform it, separated by commas.
The type conversion
Despite the flexibility, according to opinions, PHP regarding the types of variables, it may be necessary to explicitly convert a variable from one type to another. This is especially true for variables from a form, the latter being an essential tool of communication of the client to the server. These variables are always of type string.
To convert a variable from one type to another, use the following syntax:
$result = (desired_type) $myvar;
If you create so much of a new variable of the desired type from the first variable, it retains its original type. If you do not have reason to fear losing the initial value, you simply give the same name to both variables.
In the following example, you turn a string successively to a decimal integer and then finally boolean:
<?php $var = "3.52 km"; $var2 = (double) $var; echo "\$var2 =",$var2, "<br />"; // prints "$var2 = 3.52" $var3 = (integer) $var2; echo "\$var3 =" ,$var3, "<br />"; // prints "$var3 = 3" $var4 = (boolean) $var3; echo "\$var4 =" ,$var4, "<br />"; // prints "$var4 = 1" is true ?>
You also have the option of changing the type of the variable itself using the settype () function, whose syntax is:
• boolean settype($var,”desired_type”)
It returns TRUE if the operation is performed and FALSE otherwise. With this feature, the previous code becomes:
<?php $var = "3.52 km"; settype ($var, "double"); echo "\$var =" $var, "<br />"; // print "$var = 3.52" settype ($var, "integer"); echo "\$ var =" $var, "<br />"; // print "$var = 3" settype ($var, "boolean"); echo "\$var =" $var, "<br />"; // print "$var = 1" is true ?>
The predefined variables
PHP has a large number of predefined variables, which contain information both at the server and all data that can pass between the post client and server, as the values entered in a form, the cookies or sessions.
Since PHP 4.1, these variables are presented in the form of tables, accessible any point of any script. We call these superglobal arrays. A brief table description of these variables without detailing the contents because a many of them are not of immediate practical value. You will have all precision required on their use as you will use in the course of the work. Refer to the section on the tables to read the content of these variables.
Table – The PHP server variables
$GLOBALS | Contains the nameand value ofall global variablesof the script.Variable namesare the keyof this table. $GLOBALS[“myvar”] retrieves thevalue of the variable$myvaroutside itsvisibility zone |
$_COOKIE | Contains the nameand value of thecookies stored onthe client.The names ofcookies the keyof this table. BeforePHP4.1, this variable was named$HTTP_COOKIES_VARS. |
$_ENV | Contains the nameand value of theenvironment variables thatarechangingaccording to theservers. BeforePHP4.1, this variable was named$HTTP_ENV_VARS. |
$_FILES | Contains the names offiles downloaded fromthe client. BeforePHP4.1, this variable was named$HTTP_FILES_VARS. |
$_GET | Contains the nameand value ofdata from aform sent bythe GET method.The namesof the form fieldsare the keyof this table. BeforePHP4.1, this variable was named$HTTP_GET_VARS. |
$_POST | Contains the nameand value ofdata from aform sent bythe POST method.The namesof the form fieldsare the keyof this table. BeforePHP4.1, this variable was named$HTTP_POST_VARS. |
$_REQUEST | Contains all of thesuperglobals$_GET, $_POST, $_COOKIEand$_FILES. BeforePHP4.1,this variable doesnot exist. |
$_SERVER | Contains informationrelatedto the Web server, such as the contents ofHTTP headersor name runningscript.Let us rememberthe following variables: $_SERVER [‘HTTP_ACCEPT_LANGUAGE’], which contains the language code of theclient browser. $_SERVER[“HTTP_COOKIE”], which contains the nameand value ofreadcookieson the client. $_SERVER[“HTTP_HOST”], which gives the domain name. $_SERVER[“SERVER_ADDR”], which specifies the IP addressof the server. $_SERVER[“PHP_SELF”], which contains the name of thecurrent script. Weoftenusein forms. $_SERVER [‘QUERY_STRING’], which contains the query stringused to access thescript. |
$_SESSION | Contains all thenames ofsession variablesand their values. |