EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Variables in PHP

Home » Software Development » Software Development Tutorials » PHP Tutorial » Variables in PHP

Variables in PHP

Introduction on Variables in PHP

The following article, variables in PHP, provides an outline for the various variables available in PHP. Each variable stores some kind of information where information is a value. This value can be a number, a string, boolean, array or it can be an object, a resource also and so on.

How to Declare Variables in PHP?

The variables declared store information. There are certain things one must know about declaring variables in PHP.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  1. Variables declared always begin with a dollar sign ($). A variable name must begin either with a letter or an underscore but not with a number.
  2. Variables do not contain spaces and these variable names are case sensitive example $fruit is different from $From.
  3. Variables declaration uses assignment operator ‘=’ wherein the variable name is on the left side of the operator and the expression on the right side of the operator.
  4. As we know that PHP is a loosely typed language, the variables declared do know in advance what type of the variable it will be, meaning that it can be declared as a number or a string or an array or anything else.
  5. Since the values of the variables are not constant, these values can be converted from one value to another value as and when required.

How to Initialize Variables in PHP?

From the previous, we know that PHP is a loosely typed language and we need not declare the type like whether the variable is of integer, or string or boolean type before using it as it happens in other languages. The type of the variable depends upon the value it stores. Let us learn through examples.

Here in the below example, we see that the height is a float value and the base is an integer value and based on these values we have calculated the area of the triangle.

Code:

<?php
// example to demonstrate the intialization of variables
$height = 10.5;           //float value
$base = 50;               //integer value
// calculating area of a triangle
$area_of_triangle = ($height * $base) / 2;
// printing area of the triangle
echo 'Area of the triangle is '. $area_of_triangle;
?>

Output:

Initialize variables in PHP

Below code shows all valid and invalid ways of initializing the variables in PHP.

  1. // invalid because of starts with a number

$5input = 'Demo';

  1. // valid because of starts with an underscore

$_input = 'Demo';

  1. // valid

$input = 'Demo';

  1. // valid because it starts with an underscore followed by number and string of characters which is allowed

$_5input = 'Demo';

Types of Variables with Examples

Variables store values. These values assigned to the variables define what type of variable it is. There are eight data types:

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,726 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

Types of Variables

Let us learn each in detail.

1. Integer

An integer is a whole number. This integer can be positive or negative. (if no significant meaning it is positive) It compulsorily has at least one digit ranging from 0 to 9, with no comma or blanks. It does not have a decimal point. Integers have different notations like

  1. decimal(base 10)
  2. hexadecimal(base 16, prefixed with 0x)
  3. octal(base 8, prefixed with 0)

optionally preceded with a sign either – or +

<?php
//example to demonstrate an integer datatype
$x = 6900;
$y = 45;
//var_dump tells us about the datatype and value of the input number
var_dump($x);
echo '<br>';
var_dump($y);
?>

Output:

Output of Integer

2. String

A string is a sequence of characters or letters. A string can hold a sequence of numbers, special characters, arithmetic values also. It can be a combination of all as well. To represent a string we use single or double-quotes.

<?php
//example to demonstrate string datatype
$input = 'Apple';
echo '<br> $input is my favorite fruit';
echo "<br> $input is my favorite fruit";
?>

Output:

Output of String variable

3. Boolean

This data type can hold one of two values either a true or a false, where true is 1 and false is blank.

<?php
//example to demonstrate boolean datatype
$input = true;
// print true
echo "<br> True is ".$input;
$input_value = false;
// print false
echo "<br> False is ".$input_value;
?>

Output:

 Output of Boolean

4. Float

A number with a decimal point or using an exponential form is called a floating-point number or is of type float.

<?php
//example to demonstrate float datatype
$input = 123.45;
$input_value = 9.e5;
var_dump($input);
echo '<br>';
var_dump($input_value);
?>

Output:

Output of Float Variable

5. Object

An object is a data type that stores data. Along with data it also stores information about the processing of the data. An object is declared explicitly by declaring a class. Class is defined with the class keyword. A Class is a structure that contains data members and data methods.

A class is instantiated and the object is created, and through this object now we can access the members and methods of the class.

<?php
//example to demonstrate object datatype
class Subject{
//defining a string property
public $string = "My favourite subject is Maths";
//defining a method that returns the string property
function display() {
return $this->string;
}
}
//instantiating an object of a class
$object = new Subject;
echo $object->string;
?>

Output:

Output of Object Variable

6. Array

It is a collection of similar and dissimilar data types. An array is declared in the form of key-value pair.

<?php
//example to demonstrate array datatype
$directions= array('East','West','North','South');
var_dump($directions);
echo '<br>';
echo $directions[2] echo '<br>';
echo $directions[0];
?>

Output:

Output of Array

7. NULL

When no value is assigned to a variable and the variable is empty we can use NULL value.

<?php
//example to demonstrate NULL datatype
$input = 'Demo Test';
var_dump($input);
echo '<br/>';
$input = NULL;
var_dump($input);
?>

Output:

Output of Null Variable

8. Resource

A resource a special variable related to an external resource which can be file handling, database connectivity or others

<?php
//example to demonstrate resource datatype
//establishing a connection to database with default values
$connection = mysql_connect("localhost", "root", "");
var_dump($connection);
?>

Recommended Articles

This is a guide to Variables in PHP. Here we discuss what are variables in PHP, how do we declare variables, how do we initialize variables, and finally what are different types of variables in PHP. You may also look at the following articles to learn more –

  1. PHP Math Functions
  2. How to Connect Database to PHP?
  3. PHP String Functions
  4. What is PHP Array?

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More