PHP Variables and PHP Built-in Functions with example codes
Table of Contents
What are the PHP Variables?
Definition and syntax:
PHP Variables are intended to store data that will be used and can be modified when running the program. The PHP language, like the Perl language, uses a particular form of syntax for defining a variable. PHP Variables are represented with a “$” character prefixing the identification of this variable. For example, to declare a new name variable “myVariable”, just call it $myVariable inside the source code. Identifiers prior to their use. The PHP Variables are therefore said to be untyped, that is to say that a variable can take a character string value and then be used to contain an integer. The type is defined when this variable is assigned. It is partly this great flexibility of use which makes PHP a language simple and fast to access. In the example below, you can see how easy it is to use PHP Variables:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php $myVariable = "0"; // $myVariable is a character string $myVariable = $myVariable + 1; echo $myVariable; // Returns "1" and is now an integer $myVariable = 1; // $myVariable is now an integer $myVariable = $myVariable / 2; // $myVariable is now of type double $myVariable = 1 + 2 ." Long live PHP!"; echo $myVariable; // $myVariable is of type integer and returns 3 ?> |
The name of the variable can be defined by all alphanumeric characters as well as by the character ’_’, but it cannot start with a number. $myVariable, $_myVariable, $myVariable1 are valid PHP Variables. On the other hand, $ 1maVariable will cause a syntax error.
Amazon Purchase Links:
*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!
What is PHP $ and $$ variables Or Dynamic PHP Variables:
Dynamic PHP Variables are variables whose name depends on other PHP Variables. The names of these PHP Variables are therefore constructed dynamically while executing PHP code.
The example below is much more telling than a long speech:
1 2 3 4 5 6 7 8 9 |
<?php $var = "I am developing in PHP."; $dyn = "var"; echo $$dyn; // Displays "I am developing in PHP."; ?> |
Thus, by simply writing $$dyn we get the value of the variable whose name is contained in $dyn, that is, $var. The use of dynamic PHP Variables is generally not necessary, as they can, although often to be advantageously replaced by the use of tables, but who knows … it is possible that it will help you out one day!
It is often preferable, and sometimes essential, to put the name of the PHP Variables between braces. This will allow you, for example, to create a variable name with a part variable and a fixed part, as is the case in the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $prefix = "PHP"; $suffix = "it's nice"; $dyn = "pre"; echo ${$dyn} fixed; // Will display PHP $dyn = "suff"; echo ${$dyn} fixed; // Show it is nice ?> |
The result would obviously have been quite different if we had used $dynfix. The problem is identical when it comes to selecting an element of an array; $$dyn [0] is ambiguous, unlike $ {$dyn [0]} and $ {$ dyn} [0].
Types of PHP Variables:
As we have seen, PHP variables do not have a predefined type. Yet a developer may need to manipulate types for the needs of an application and conversion problems may not cause errors, but return results surprising and embarrassing. To avoid this, the PHP language has a set of functions which allows you to set and retrieve the type of a given variable. We can classify the different possible types into three categories: scalar types, compounds and special types.
Table 1: Definitions of the four scalar types
Type | Description | Example |
int (or integer)
|
The int type is used to contain
integers (numbers without comma). Values can range from –2147483648 to 2147483647. |
$myVariable = 2;
$myVariable = −4; $myVariable = 2002; |
double (or real or float) | The double type is used to define
decimal numbers, that is to say with a floating point. |
$myVariable = 1.0;
$myVariable = −0.1 $myVariable = 3.1415972; |
String | The type string defines a string
of characters. |
$myVariable = “Long live it php! “;
$myVariable = “1”; |
boolean (or bool) | The boolean type defines a variable
taking binary type values: TRUE or FALSE. |
$myVariable = TRUE;
$myVariable = FALSE; |
1 2 3 4 5 6 7 8 9 |
<?php $dec = 16; // Classic assignment in base 10 $hex = 0x10; // The 0x indicates the assignment in hexadecimal $oct = 020; // The single 0 in front indicates the assignment in Octal ?> |
$dec, hex and $oct have the same value but expressed in a base different. Note that it is not possible to express a number directly in its form binary.
Table 2: The two compound types of PHP variables
Type | Description | Example |
Array | Designates an array type (set of
values). |
$myArray = array (2,
“Great, PHP!”, “key” => “value”); $ myArray [2] = “Top”; |
Object | Designates an object type (variable
having its own properties, attributes and methods).
|
class MyClass
{ } $myObject = new MyClass() |
Table 3: The two special types supported PHP Variables
Type | Description |
resource | Represents a reference (e.g .: connection identifier to a database
or any other source). |
NULL | The NULL type variable represents a variable that has no value. |
Although the type of PHP Variables is defined at their initialization, it is still possible to force a variable into a given type.
PHP Built-in Functions:
Built-in Function settype():
Assigns a type to a variable.
Syntax:
boolean settype ($variable, string $type)
$variable:
Variable whose type we want to set.
$type:
Character string specifying the type that we want to assign to the variable.
It can be either:
integer for an integer type.
double for a real type.
string for a character string.
array for an array.
Return:
TRUE on success or FALSE (eg: invalid type name).
To retrieve the type you will use the gettype () function.
Built-in Function getType ():
Returns the type of the variable.
Syntax:
string getType ($variable)
$variable:
Variable whose type we want to determine.
Return:
The different possible return values are:
integer for an integer type.
double for a real type.
string for a character string.
array for an array.
object for an object.
resource for a resource (a pointer to …).
user function for a function created by the user.
unknown type for an unknown type.
The code below is a good example of this use:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php setType ($abc, "integer"); // The variable is of type integer echo getType ($abc); // Returns "integer" $ i = 2 + 2; echo getType ($i); // Returns "integer" $i = "I like the number". $i; // Concatenate a string with an integer echo getType ($i); // Returns "string" ?> |
The cast:
To remedy the problems that you may encounter in your handling of conversion, the developer has the option of using cast (or type casting). Under this somewhat barbaric term, hides the possibility of creating a new variable containing the value another with a different but compatible type. Thus, the cast allows a programmer to modify the type of this PHP Variables during the execution of his program, that either to test for equality or to perform operations between two variables of different types. The cast is used, as for the C language, by writing the type in parentheses before the name of the variable, as shown in the example below:
1 2 3 4 5 6 7 8 9 10 11 |
<?php $myInteger = 10; // $myInteger is an "integer" $myString = (string) $myInteger; // $myString is a character string ?> |
The different possible conversions are therefore:
- (array) to convert to array type.
- (boolean) or (bool) to convert to boolean type.
- (double), (float) or (real) to convert to real type (decimal).
- (int) or (integer) to convert to integer type.
- (object) to convert to type object.
- (string) to convert to type string.
In the following example, we show how, from converting to an array or an object, a programmer can recover the data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $myVariable = "Great, more PHP!"; $array = (array) $myVariable; echo $array [0]; // returns "Great, more PHP!" $object = (object) $myVariable; echo $object-> scalar; // returns "Great, more PHP!" ?> |
Note that converting a scalar type variable (int, double or string) into the type object will create an attribute named scalar and containing the value of the variable.
The references:
PHP allows to create a reference to an existing variable. In the same way as with the C language, you can directly access a memory area containing a variable. The reference to a variable allows you to create a new variable that uses the same zone memory as the original variable. To do this, you must indicate it using the character ’&’ in front of the variable name, such as show the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $var1 = "Hello"; $var2 = & $var1; // $var1 and $var2 are two same names for the same variable $var2 = "Goodbye"; echo $var1; // Poster Goodbye ?> |
Test a variable:
In your data manipulations, you may need to test the existence or the type of PHP Variables you use. For this we use a very useful set of functions.
Built-in Function isSet ():
Determines whether a variable exists (has been initialized).
Syntax
boolean isSet ($variable)
$variable
Variable that we want to test.
return
TRUE if the variable exists and FALSE otherwise.
Built-in Function unset():
Destroys the variables.
Syntax
void unset ($variable1 [,$variable2 [, …]])
$variable1, …
The variables to destroy.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php echo isSet ($test); // Returns FALSE (which displays nothing) $test = ""; echo isSet ($test); // Returns TRUE (which displays 1) unset ($test); echo isSet ($test); // Returns FALSE (which displays nothing) ?> |
Likewise, the empty () function determines whether a variable has a value not zero or not.
Built-in Function empty():
Determines whether a variable has a non-zero value or not.
Syntax
boolean empty ($variable)
$variable
Variable that we want to test.
return
TRUE if the variable does not exist, is an empty string (’’) or is 0, NULL, FALSE otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php $var1=0; $var2=1; $var3=""; $var4="hello"; if(empty($var1)) echo '$var1 "empty" <br>'; else echo '$var1='.$var1.'<br>'; if(empty($var2)) echo '$var2 "empty" <br>'; else echo '$var2='.$var2.'<br>'; if(empty($var3)) echo '$var3 "empty" <br>'; else echo '$var3='.$var3.'<br>'; if(empty($var4)) echo '$var4 "empty" <br>'; else echo '$var4='.$var4.'<br>'; ?> |
To destroy a variable, use the unset () function. In order to test the type of PHP Variables, PHP has a series of very convenient functions:
is_bool (),
is_int (),
is_double (),
is_numeric (),
is_string (),
is_array (),
is_scalar (),
is_object (),
is_resource ()
is_NULL ().
All of these functions are used in the same way. They return TRUE if the type of the variable passed as a parameter is exactly the type sought, and FALSE otherwise.
Built-in Function is_bool ()
Determines whether a variable is of type Boolean.
Syntax
boolean is_bool ($variable)
$variable
Variable which we want to determine if it is of Boolean type.
return
TRUE if the variable is of Boolean type, FALSE otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $var = 1; echo is_bool ($var); // Don't return anything, the test result is false $var = TRUE; echo is_bool ($var); // Returns 1, the result of the test is true ?> |
Built-in Function is_int ()
Determines whether a variable is of type integer.
Syntax
boolean is_int ($variable)
$variable
Variable which we want to determine if it is of integer type.
return
TRUE if the variable is of integer type, FALSE otherwise.
is_int () is actually an alias of is_long () of which is_integer () is another alias.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $var = "15"; echo is_int ($var); // Don't return anything, the test result is false $var = 15; echo is_int ($var); // Returns 1, the result of the test is true ?> |
Built-in Function is_double ()
Determines whether a variable is of type real (decimal).
Syntax
boolean is_double ($variable)
$variable
Variable which we want to determine if it is of real type.
return
TRUE if the variable is of real type, FALSE otherwise.
is_float () and is_real () are aliases of the is_double () function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $var = 15; echo is_double ($var); // Don't return anything, the test result is false $var = 15.0; echo is_double ($var); // Returns 1, the result of the test is true ?> |
Built-in Function is_numeric ()
Determines whether a variable is a number or a character string representing a number.
Syntax
boolean is_numeric ($variable)
$variable
Variable which we want to determine if it is of type number or string of characters representing a number.
return
TRUE if the variable is of type number or string representing a number, FALSE otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php $var1 = "fifteen"; echo is_numeric ($var1); // Don't return anything, the test result is false $var2 = 15; echo is_numeric ($var2); // Returns 1, the result of the test is true $var3 = "15"; echo is_numeric ($var3); // Returns 1, the result of the test is true $var4 = 15.0; echo is_numeric ($var4); // Returns 1, the result of the test is true ?> |
Built-in Function is_string ()
Determines whether a variable is of type string.
Syntax
boolean is_string ($variable)
$variable
Variable which we want to determine if it is of type character string.
return
TRUE if the variable is a character string, FALSE otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $var = "15"; echo is_string ($var); // Returns 1, the result of the test is true $var = 15; echo is_string ($var); // Don't return anything, the test result is false ?> |
Built-in Function is_array ()
Determines whether a variable is of type array.
Syntax
boolean is_array ($variable)
$variable
Variable which we want to determine if it is of array type.
return
TRUE if the variable is of array type, FALSE otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $var1 = 15; echo is_array ($var1); // Don't return anything, the test result is false $var2 = array (15); echo is_array ($var2); // Returns 1, the result of the test is true ?> |
Built-in Function is_object ()
Determines whether a variable is of type object.
Syntax
boolean is_object ($variable)
$variable
Variable which we want to determine if it is of type object.
return
TRUE if the variable is of object type, FALSE otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php class Test { var $ x; } $var = new Test (); $var-> x = "I am an attribute"; echo is_object ($var); // Returns 1, the result of the test is true echo is_object ($var-> x); // Don't return anything, the test result is false ?> |
Built-in Function is_scalar ()
Determines whether a variable is of scalar type.
Syntax
boolean is_scalar ($variable)
$variable
Variable which we want to determine if it is of scalar type.
return
TRUE if the variable is of scalar type, FALSE otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php $var1 [0] = 3.14; $var2 = 3.14; $var3 = "pi"; echo is_scalar ($var1); // Don't return anything, the test result is false echo is_scalar ($var1 [0]); // Returns 1, the result of the test is true echo is_scalar ($var2); // Returns 1, the result of the test is true echo is_scalar ($var3); // Returns 1, the result of the test is true ?> |
Built-in Function is_resource ()
Determines whether a variable is of type resource.
Syntax
boolean is_resource ($variable)
$variable
Variable which we want to determine if it is of type resource.
return
TRUE if the variable is of type resource, FALSE otherwise.
Built-in Function is_NULL ()
Indicates whether a variable is NULL.
Syntax:
boolean is_NULL ($variable)
$variable
Variable which we want to determine if it is NULL.
return
TRUE if the variable is NULL, FALSE otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $var = 0; echo is_NULL ($var); // Don't return anything, the test result is false unset ($var); echo is_NULL ($var); // Returns 1, the result of the test is true ?> |
External PHP Variables:
We can differentiate two types of external PHP Variables:
- Environment PHP Variables (from the server);
- Variables passed as a parameter when calling the page (either via a form or via URL).
Environment PHP Variables:
Environment PHP Variables are variables automatically generated by PHP from from the data retrieved from the server or from the client request header.
These PHP Variables in fact constitute two tables of global scope (accessible from any which place in the script):
- $ _ENV contains the “real” server environment PHP Variables, i.e. all PHP Variables that the account under which the web server is running (eg: PATH) may have inherited.
- $ _SERVER contains, for its part, the “internal” PHP Variables of the server (name and version of the server, IP address, etc.) as well as those retrieved from the client (client IP address, type of browser, etc.).
You can simply view all the environment variables on the generated page by the phpinfo () function.
Another possibility to retrieve the list of variables is to use the function get_defined_vars (); it allows you to retrieve the list of all the PHP Variables in an array defined. The returned array then contains all the environment PHP Variables, but also all user-defined PHP Variables.
Built-in Function get_defined_vars ()
List all defined variables.
Syntax
array get_defined_vars (void)
return
All the PHP Variables in an associative array where the names of the keys are the variable names and the values of the variables.
The example below generates an HTML table containing the list of PHP Variables and their values when the code is executed:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<html> <body> <?php $a1 = "first variable"; $a2 = "second variable"; echo "<table border = 1>"; $a = get_defined_vars (); while (list ($ key, $ val) = each ($ a)) { echo "<tr>"; echo "<td> \ $". $ key. "</td> <td>". $ val. "</td>"; echo "</tr>"; } echo "</table>"; ?> </body> </html> |
The array $ _ENV is generally not of great interest except in a few cases individuals. You can also retrieve the values using the getEnv () function.
Built-in Function getEnv ()
Returns the value of an environment variable.
Syntax
string getEnv (string $ environmentVariable)
$variable Environment
Environment variable whose value we want to determine.
Return
The value of the environment variable or FALSE if there is an error
It is very easy to modify environment variables using the putEnv () function. The values thus set by the developer only last as long as the script is running and, as soon as it ends, the default environment is restored. But, as changing some values can cause problems with security, the system administrator has the ability to prevent certain changes. It is Moreover, by default, the case of the LD_LIBRARY_PATH variable (from a UNIX / Linux system) which, if it were to be changed, could possibly allow hackers to hide the presence of a library (perhaps used by the web server) for the benefit of another more malicious. Thus, the safe_mode_protected_env_vars directive of the configuration file php.ini contains a list of environment PHP Variables that the developer cannot modify. Likewise, if safe_mode (protected mode) is enabled (which is not the case by default), only PHP Variables starting with the prefixes specified in safe_mode_allowed_env_vars may be changed.
Built-in Function putEnv ()
Set a new value for the environment variable.
Syntax
void putEnv (string $assignmentString) $stringAssignment Character string of the form “<variable name> = <value>”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $ip = getEnv ("REMOTE_ADDR"); // returns the user's IP address putEnv ("NEW_IP = 127.0.0.1"); // Define a new environment variable echo getEnv ("REMOTE_ADDR"); // Displays 127.0.0.1 ?> |
The $ _SERVER array, for its part, will allow us to perform many operations.