What is variables?
Variables are used to store information to be referenced and manipulated in a computer program. Their sole purpose is to label and store data in memory, those are then available publicly or privately.
PHP Variables
In PHP to declare a variable $ sign, follows the name of the variable.
PHP Example:
<?php
$text = "Hello World!";
$a = 40;
$b = 23.5;
echo $text;
echo $a;
echo $b;
?>
When above program is executed, the variable $text will hold the value Hello World and variables $a and $b will hold 100 & 23.5 respectively.
When assigning a text value to variable, put quotes around the value. Unlikely other programming language, PHP has no command to declare a variable.
A variable can have a short name (like x and y) or a more descriptive name (age, first_name, salary, gender).
PHP variables definition rules:
- A variable starts with the
$
sign, followed by the name of the variable - A variable must start with a letter or the underscore character
- A variable can’t start with a number
- A variable can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- variables are case-sensitive like: (
$name
and$NAME
are two different variables)
Python Variables
Likewise PHP, Python also has no command for declaring a variable. A variable is created at the moment they are assigned a value.
Python Example:
age = 30
country = "Pakistan"
print(age)
print(country)
Variables do not need to be declared with any particular type, and can even change type after they have been set.
y = 100 # y is of type int
y = "Pakistan" # y is now of type str
# Type casting
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Unlikely PHP, in Python string variables can be declared either by using single or double quotes.
country = "Denmark"
# is the same as
country = 'Denmark'
In Python likewise PHP a variable can have a short name (like x and y) or a more descriptive name (age, first_name, salary, gender).
Rules for Python variables:
- 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 (name, Name and NAME are three different variables)