Variables and Constants in PHP

Estudies4you
Variables and Constants in PHP

WORKING WITH VARIABLES AND CONSTANTS

Learning Objectives
At the end of this topic, you will be able to:
  • Describe variables and constants Create and work with variables and constants
  • List the data types supported by PHP
  • Use all the data types supported by PHP
  • Describe all operators types supported by PHP
  • Use all the operator types supported by PHP

Variables in PHP
  • Variables are used to store information.
  • Naming convention:
  • Variables in PHP are denoted by a $ sign followed by a variable name
  • Variable names must begin with a letter or an underscore character
  • Variable names must contain alpha-numeric characters or underscores
  • Variable names must not contain spaces
  • Variable names are case sensitive Variable names do not need to be declared in PHP

Working with Variables
  • Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right side
  • Variables in PHP can be defined before they are assigned, but this is not mandatory
  • Variables in PHP do not have intrinsic types, that is, a variable doesn't have to defined as an integer, or string. A variable can store any type of data
  • Variables hold the most recent value that has been assigned to them
  • Variables are created the moment a value is assigned to them
  • Variables in PHP allows type conversion, if required

Examples:
$basic=2000;
$da=1000;
$total_salary=$basic+$da;
$message="Hello world";
$avg=50.56;

Script: Variable.php
Example: Working with Variables

<?php
$msg="Hello";
$msg1="Kiran";
$a_number=4;
$anotherNumber=8;
$total=$a_number+$anotherNumber;
$msg2=$msg . $msgl;
echo $msg2; echo $total;
?>

Output
Hello Kiran
12


To Top