PHP Variables

In PHP, variable main way to store the values or data. Variables are containers that store numeric values, character values, strings, and memory addresses.

There are few rules of PHP Variables:

  1. A variable always starts with $ symbol, followed by the variable name. Like - $a 
  2. A variable name can't start with a number. It always starts or contain with alphanumeric or underscore (i.e., ‘a-z’, ‘A-Z’, ‘0-9 and ‘_’) in their name.
  3. PHP variables are case-sensitive, i.e., $var and $VAR. Both are different variables and hold different values.
  4. A variable name can't contain spaces.

In PHP variable can be declared as: $var_name = Pass Value

Some Examples of PHP Variables: 

1) How to declare variables.

<?php 

	//declaring variables
	$text = "This is my First variable"; // string variable
	$numeric = 10; //integer variable

	//Outputs of Variables
	echo $text; //Output : This is my First variable
	echo $numeric: //Output : 10

?>

 

2) Show output of text with variable.

<?php 

	$text = "Elevenstech Web Tutorials";

	echo "Welcome to $text"; 

	//Output : Welcome to Elevenstech Web Tutorials
	
?>

 

3) How to concatenate text with variables.

<?php 

	$text = "Elevenstech";

	echo "Welcome to ".$text." Web Tutorials" ; 

	//Output : Welcome to Elevenstech Web Tutorials
	
?>

Note: The PHP concatenation operator (.) is used to combine two string values to create one string.

 

4) How to sum two variables in PHP.

<?php 

	$number1 = 10;

	$number2 = 15;

	//result variable hold the sum of two numbers.
	$result = $number1 + $number2;

	echo "The result is ".$result;

	//Output : The result is 25
	
?>