PHP Variables

Variables in any programming language are used to hold/store data such as String, Numeric (int, float, double), Array, or Objects.

$test_variable_name = "Paolo";
$counter = 10;

PHP variable is like an ice cream cone (see image below), the cone itself is the variable while the ice cream is the data. It can be in String, Numeric, Array, or an Object data-type.

PHP Variable Scope

This refers to where a variable is accessible in the script.

  • Global Variables – These type of variables can be access anywhere outside a function.
  • Local Variables – These type of variables can only be access only inside the function.

Diagram below shows the variable scope:

Declaring a Variable

We use (=) equal sign to assign a value to a variable.

$x = "value"; // String data-type. Variable $x has now a value of a string "value".
$x = 'value'; // String data-type. Variable $x has now a value of a string "value".

$x = "100";   // numeric data-type. Variable $x has now a value of numeric 100.
$x = '100';   // numeric data-type. Variable $x has now a value of numeric 100.
$x = 100;     // numeric data-type.  Variable $x has now a value of numeric 100.

$x = array(0 => 'value1',  "1" => 'value2'); // Array data-type.
$x = array("a" => array("k" => "v")); // multi-dimensional Array.

$x = false; // boolean
$x = true;  // boolean

$x = new ObjectName();	// Object

How to Declare a PHP Variable

  • A PHP variable must starts with dollar sign ($).
    • $varname
  • The first character of a PHP variable name must be underscore or letter.
    • $testname
    • $_test
  • PHP variable name will only contain alpha-numeric characters and underscore such as a-z, A-Z, 0-9, and _.
  • Invalid PHP variable names are:
    • $8thvar // starts with number
    • $a#rr // contains invalid character #

Sample Programs

1) This sample program will assign variables a value with String, Interger, and Float data-types.

<?php
$str = "Hello World!";
$int_sample = 4;
$float_sample = 8.25;

echo $str ."<br/>";
echo $int_sample . "<br/>";
echo $float_sample . "<br/>";
echo "int_sample + float_sample = " . ($int_sample + $float_sample);
?>

OUTPUT:

Hello World!
4
8.25
12.25

2) Sample program for global variable usage.

<?php
$name = "Nino Paolo Amarillento";

function myFunc(){
	$name = "Louellyn Bacalla";
}

echo $name;
?>

OUTPUT:

Nino Paolo Amarillento

3) Sample program for local variable usage.

<?php
$name = "Nino Paolo Amarillento";

function myFunc(){
	$name = "Louellyn Bacalla";
	echo $name;
}

myFunc();
?>

OUTPUT:

Louellyn Bacalla
This entry was posted in PHP Beginners Course, PHP Tutorial. Bookmark the permalink.

One Response to PHP Variables

  1. Margery says:

    Super knowledge! I have been previously hunting for something similar to this for some time now. Many thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *


*