What is PHP Variables?
The Variables in PHP are characters that store a value or information such as text or integers in code.
Declaring a PHP variable, use the dollar sign ($) followed by the variable name.
PHP variables are used to store values, expressions, letter names, or long sentences.
There are five basic rules for PHP variables:
- PHP variables must begin with a dollar $ sign before the variable name.
- It must begin with a letter or underscore.
- Variables can only contain alphanumeric characters and underscores in the variable name.
- Do not use spaces in variable names.
- Be case-sensitive when defining PHP variables, as capitalization matters.
Important things you should know about variables in PHP
Creating variables in PHP
Assigning values creates variables in PHP, serving as the primary method for storing information within them.
Here are some Important things you should know about variables in PHP:
- It doesn’t need to declare variable data types and it will automatically parse the values and convert them to the correct data type.
- PHP variables require assignment before use and have invalid values otherwise.
- Assigning a value to a variable uses an assignment operator (=).
Here is the syntax for declaring a string, integer, and float in PHP variable:
Example:
<?php
$sampleStr = "Souce code hero"; // declaring a String
$sampleInt = 55; //declaring a Integer
$sampleFloat = 32.7; //declaring a float
echo"this is a string: $sampleStr </br> ";
echo"this is an integer: $sampleInt </br>";
echo"this is a float: $sampleFloat </br>";
?>
Output:
this is a string: Souce code hero
this is an integer: 55
this is a float: 32.7
What are the Different Types of PHP Variables?
By the way, to test the following examples, we also have an Online PHP Compiler for you!
Data types used to declare or create PHP Variables:
Strings
A string in PHP is a sequence of characters, such as text or numbers, enclosed in single quotes (‘) or double quotes (“).
$string_a = "Welcome to Source Code Hero"; //using double quotation marks
$string_b = 'Welcome to Source Code Hero'; //using single quotation marks
$string_c = "Sample numbers like 1234"; //integer can be used as String using Quotation marks
$string_d = "Sample symbols like !@#$%^&*()"; //using symbols
$string_e = " "; //can be an empty strings
Single-quoted strings are treated almost literally, while double-quoted strings replace variables with their values and sequences of special characters.
Additional Example Code using Strings:
<?php
$codeVar = "Source Code Hero";
$str_sample = 'This will not print the value of $codeVar';
// As you may have noticed, we use a double quote to use the character sequence \n.
echo $str_sample."</br>";
$str_sample = "Using double quotes this will print the value of $codeVar";
echo $str_sample;
?>
Output:
This will not print the value of $codeVar
Using double quotes this will print the value of Source Code Hero
There is absolutely no arbitrary limit on how long a string can be. If you have enough memory, you should be able to create strings of any length.
PHP performs the following two operations on strings separated by double quotes (““):
- Some strings that start with a backslash () are converted to special characters.
- Variable names starting with ($) are converted into strings indicating their values.
The list of escape-sequence replacements:
- Using a backslash inside a string use \.
- Using a double-quote inside a string use \”.
- Tab a character inside a string use \t.
- Creating a new line use \n or </br>.
- Using a dollar sign inside a string use \$.
Integers
In PHP, integers are whole numbers without decimal parts.
Example:
<?php
$interger1 = 423;
$interger2 = 177;
$total_int = $interger1 + $interger2;
echo "The amount is $total_int";
?>
Output:
The amount is 600
Booleans:
In PHP, booleans are fundamental data types that represent truth values, meaning they can only be true or false.
Example:
$Is_child = false;
$Is_adult = true;
NULL
In PHP, NULL is a special value representing the absence of a value.
Example:
$my_Code = NULL;
Doubles
In PHP, Doubles (also called floats) is a data type used to represent floating point numbers.
Example:
<?php
$firstSem = 88.23498;
$secondSem = 89.67433;
$Total = $firstSem + $secondSem;
echo $Total;
?>
Output:
177.90931
Arrays
In PHP, an Array is an ordered collection of elements, where each element has an index, starting from 0, which can store different data types within the same array.
Example:
<?php // Numeric array
$foods = ["Adobo", "Burger", "Bread"];
// Accessing first element of an Array
echo "First Food: " . $foods[0]
?>
Output:
First Food: Adobo
Objects
In PHP, they represent complex data structures that contain both data (properties) and functions (methods) associated with that data.
The Programmer defined classes that can contain two classes with different values and class-specific functions.
Example:
<?php
class Sample {
public $name;
public function sourceCode() {
echo "Welcome to Source Code Hero $this->name!";
}
}
$adrian = new Sample();
$adrian->name = "Adrian";
$adrian->sourceCode(); // Output: Welcome to Source Code Hero Adrian!
?>
Output:
Welcome to Source Code Hero Adrian!
Resources
In PHP, a Resource represents a reference to an external entity or system that your program interacts with.
This entity could be a file, database connection, network socket, image, XML parser, or even standard input/output streams like STDIN and STDOUT.
Examples:
Reading a File.
$fileHandle = fopen("myfile.txt", "r");
$content = fread($fileHandle, filesize("myfile.txt")); // Read content
fclose($fileHandle); // Close the file
Connection to a Database.
$dbConn = mysqli_connect("localhost", "username", "password", "database");
$result = mysqli_query($dbConn, "SELECT * FROM users"); // Execute query
mysqli_close($dbConn); // Close the connection
How to Check to Get the Type of Variable in PHP
To determine the variable types in PHP, using the built-in gettype() function.
This function takes a single parameter, the variable you want to control, and returns a string representing the data type of that variable.
To call the gettype() function.
The syntax of the gettype() function is:
gettype(mixed $strType): String
You must pass the variable you want to check as a function parameter.
This function then returns a string representing the type of the variable.
Here is an example of executing a function:
<?php
$string = "Source Code hero!";
echo gettype($string); // string
$boolean = true;
echo gettype($boolean); // boolean
$arrays = array(1, 2, 3);
echo gettype($arrays); // array
// pass a value directly
echo gettype(20); // integer
echo gettype(3.14); // double
?>
What are Output Variables?
In PHP you can use any variable to generate the Output.
By assigning a value to a variable and then using echo, print, or similar functions, that value becomes part of the output sent to the browser or other target environment.
The echo is used to display the output of the parameters passed.
Displays the results of one or more comma-separated strings.
The print function requires one argument each and cannot be used as a variable function in PHP.
Printing only produces character strings.
For example:
<?php
//using echo function to show the Output
$codePHP = "PHP language";
echo "Welcome to $codePHP! </br>" ;
//using print function to show the Output
$srcCode = "Source code hero";
print "Welcome to $srcCode!";
?>
Output:
Welcome to PHP language!
Welcome to Source code hero!
Difference between print and echo in PHP:
Feature | echo | |
1. Number of arguments | Accepts multiple arguments separated by commas | Accepts only one argument |
2. Return value | Doesn’t return any value | Returns 1 (true) on success, false on failure |
3. Use in expressions | Cannot be used within expressions | Can be used within expressions |
4. Performance | Marginally faster | Marginally slower |
5. Common usage | More common for general output due to its flexibility and lack of return value | Primarily used for simple debugging statements or when returning a value is required in an expression |
What is Variable Scope?
Variable scope in PHP refers to the visibility or accessibility of variables, functions, and classes in a specific
A variable scope is the part of the script where a variable can be referenced/used. context.
It is important to understand the scope of these elements because this determines where they can be viewed and edited in the program.
In PHP, there are three types of variable scope: global, local, and static.
1. Local Variables
Variables declared in a function or code block have local scope.
They are only available in that specific feature or block and variable scope is the part of the script where a variable can be referenced/used.
Example of Local Variables code:
<?php
// Function to demonstrate local variable scope
function myFunction() {
// Declare a local variable inside the function
$localVariable = "This is a local variable sample !";
echo $localVariable; // Output: This is a local variable sample!
}
// Call the function to execute its code
myFunction();
?>
Output:
This is a local variable sample!
2. Global Variables
Global Variable exists outside of any function or class and is accessible from anywhere in the script, including inside functions and methods.
Example of Global Variables code:
<?php
$globalVariable = "Variable!";
function myFunction()
{
global $globalVariable;
echo "This is a Global $globalVariable.";
}
myFunction();
?>
Output:
This is a global Variable!
3. Static Variables
A static variable is a variable declared with the static
keyword within a function. Unlike regular variables, a static variable retains its value between function calls.
Example of Static Variables code:
<?php
function counter() {
static $count = 0; // Declare a static variable $count initialized to 0
$count++;
echo "Count: $count\n";
}
counter(); // Output: Count: 1
counter(); // Output: Count: 2
counter(); // Output: Count: 3
?>
Output
Count: 1
Count: 2
Count: 3
Function parameters
Function parameters are variables that serve as placeholders for information passed when the function is called.
They allow you to customize the behavior of a function based on different input values.
Example of Function parameters code:
<?php
function greet($name, $greeting = "Hello") {
echo $greeting . ", " . $name . "!\n";
}
// Call the function with two arguments
greet("Alice", "Hi"); // Output: Hi, Alice!
// Call the function with one argument, using the default greeting
greet("Bob"); // Output: Hello, Bob!
?>
Output:
Hi, Alice! Hello, Bob!
Conclusion
We have completed the discussion on the Different Types of PHP Variables, encompassing their definition and their significance in web development.
We’ve highlighted its importance and basic sample code using the variable type.
Should you have any questions or need further clarification on the PHP Variable Type, feel free to drop us a comment below.
Your feedback is invaluable to us!