Variable & its Scope in PHP

To output the text we have seen that we printed a string “These are my Variable” with one echo command and variable in another command. But Sometimes you need to interpolate the variable in the long string then how you will do it, it can be performed in two ways as shown below:

<?php
$blogger_name=”Rahul Chanana”;
$blog=”Tekraze”;
$posts=5;
echo “This is $blogger_name from $blog, and this is my $posts th posts”;
?>

<?php
$blogger_name=”Rahul Chanana”;
$blog=”Tekraze”;
$posts=5;
echo ‘This is ‘.$blogger_name.’ from ‘. $blog.’, and this is my’.$posts.’ th posts’;
?>

Output:This is Rahul Chanana from Tekraze, and this is my 5 th post

Things Learned

  • A Text (called as the string in programming languages) can be created by enclosing symbols in ” ” or ‘ ‘.
  • If You want to print value of a variable then you can create it in two ways, by enclosing the variable in double quote as in snippet 2 or concatenation with string using dot operator as shown in snippet 3
  • Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it. Therefore PHP is a loosely Typed Language (doesn’t require any variable declaration before using it)

Rules for PHP variables:

  • A variable can have a short name (like x and y) or a more descriptive name (age, carName, total_volume).
  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ($age and $AGE are two different variables)