variables

PHP Variables

Variables serve as containers where information is stored. In PHP, these are represented by a dollar sign followed by the name of the variable. Consider the rules below:


Rules for PHP variables

  • Variables should start with the dollar ($) symbol, followed by the name of the variable.
  • A variable name should not start with a number.
  • A variable name must start with a letter or the underscore character.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive example. $strand $Str are two different variables). But it is recommended to use all lower case.

Valid and Invalid variables

Before you can use a variable, you must know which one is valid and invalid. Check some of the examples below:

Variables Result
$Str Correct
$str Correct
$___str___ Correct – use of two underscores is just fine
$_str Correct
$str1 Correct – numbers are fine at the end and after the first character
$_str Correct – underscores are acceptable characters
$10str Incorrect – variables should not start with a number
$_str’s Incorrect – single quote is a special character that should be included in a variable

Note: It is necessary to use descriptive variables when creating a php script. Example, when you are going to store the age of a person, you may use $age instead of using $xy. In this case, you can easily understand when you’re doing a bunch of codes.


Variables inside Single quote and Double quote

Let’s use a variable in string literals(single quote and double quote)


<?php

$str = 'Samuel';

//Output: My Name is Samuel
echo "My Name is $str";

//Output: My name is $str
echo 'My name is $str';
?>


Basic arithmetic operations


$x = 10;
$y = 20;

//Output: 30
echo $x + $y;

//Output: 10
echo $y - $x;

//Output: 200
echo $x * $y;


Local vs Global Variables

<?php
$str = "Samuel"; // global variable

function display() {
$str_1 = "Hello there"; //local variable

// Will display an error. $str is a global variable.
// Hence, it cannot be accessed inside the function
echo "Hello, my name is $str";

//Output: Hello there
echo $str_1;
}

display();

echo "This is outside function. I'm $str";
?>

If you have more examples, please comment below.

Leave a Reply

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