Wednesday, 10 March 2021

Php: variables

Variable is a named memory location that stores some value. You can store information in a variable and reference it later in the php program.

 

Variables in php always starts with $ symbol, followed by an uppercase/lowercase letter or _.

 

Example 1

$age = 23;

Numeric value 23 is assigned to the variable age.

 

Example 2

$name = "Krishna";

String value "Krishna is assigned to the variable name.

 

variable_demo.php

#!/usr/bin/php

<?php 

	$age = 23;
	$name = "Krishna";

	echo "Hello Mr." . $name . ", you are " . $age . " years old";
?>

Output

$./variable_demo.php 

Hello Mr.Krishna, you are 23 years old


Can I change the value of a variable?

Yes, you can change the value of a variable at any time in the program.

 

variable_value_change_demo.php

#!/usr/bin/php

<?php 

    $age = 23;
    echo "age is set to $age\n";
    
    $age = 31;
    echo "age is set to $age";
?>


Output

$./variable_value_change_demo.php 

age is set to 23
age is set to 31


Is spaces allowed in variable names?

No, spaces are not allowed in variable names. If you have a variable name with multiple words, separate them with underscore.

 

Example

$my_name

$rate_of_intrestet

$employee_rating







 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment