PHP Variable Declaration, Naming Conventions, Data Types

PHP Variable Declaration, Type, Naming Conventions

What is Variable in PHP

PHP Variables are containers which are used to store data or information.


PHP Variable Declaration

In PHP All variable names must start with a $ sign, followed by the name of the variable. Like this$variable_name

You can declare variables anywhere in the PHP script.


Assign Value to a Variable

Use the = equal sign to assign value for a variable. Like this – $name = "John Doe";

This = equal sign is called Assignment Operator.

<?php
  $name = "John Doe"; // Declaring a variable
  echo $name; // Displaying the variable value
?>
Browser Output
John Doe

Naming Conventions of a Variable

To Declare or Create a PHP Variable you need to follow some Rules –

  1. Variable Must start with a $ sign.
  2. Variable name must start with a letter or the _ underscore character.
  3. A variable name cannot start with a number.
  4. A variable name can only contain alpha-numeric characters and underscores (A to z, 0 to 9 and _ )

In PHP, variable names are case-sensitive. In the below example both are different variables –

$searchengine = "Google";
$searchEngine = "Yahoo";

PHP Data Types

You can assign all the data types in a variable, that are available in PHP.

Below, the list of the PHP Data Types with a short description –

1 – String – A string is a sequence of characters, that are inside a single or double quote.

$x = "Hello world";

2 – Integer – An integer is a non-decimal number.

$x = 123;

3 – Float – A float is a number with a decimal point.

$x = 10.5;

4 – Boolean – True or False.

$x = true;

5 – Array – Collection of multiple values.

$x = array("value1","value2");

6 – Object – An object is an instance of a class.


7 – NULL – If there is a NULL data type in a variable, then that means the variable does not have any value.

$x = NULL;

If a variable is declared without any value, then the variable is automatically assigned the NULL value.


8 – Resource – Such as Database Connection.


Official Docs of PHP Variables


Next is – PHP echo, print, echo VS print, Variable Interpolation

Previous isPHP Introduction, Setup Dev Environment, Run PHP Code

Posts Navigation


Leave a Reply

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