PHP – Variables, Types and Operators

March 23, 2014 by in category PHP, Programming tagged as , , , , , , , , , with 0 and 0
Home > Blog > PHP > PHP – Variables, Types and Operators

What is a variable?

A variable is like a custom-made box. It can only hold one thing at a time and youshould specify the type of thing you want to put in it when it’s being made.Each variable starts with a dollar sign ($) in PHP and can hold various types of data (e.g: strings (‘Hello’), integers (5), floats (3.141592), arrays ({1,2,3})). Each variable can only hold one value in it at a time but the value can be changed later on.

Explicit Type Conversion/Type Declaration

When first declaring a variable, you can choose to tell PHP what type you want to store in it and will then convert the value you give it to match.

<?php
	//This will output 3
	echo $number = (int) 3.141592;

	//This will output 5.0
	echo $number = (float) 5;

	//This will convert the string to a number and output 7
	echo $number = (int) '7';
?>

Implicit Type Conversion

PHP will automagically convert variables into the relevant type on its own without you needing to declare its type. It’s always best to think clearly of the type you need and tell PHP that you want that type to ensure everything works the way you intend it to.

PHP Operators

You can use basic mathematic operators to manipulate variables in PHP. These operators are: +, -, * (multiply), / (divide) and % (modulus – remainder of a division)

<?php
	$apples = 5;
	$price = 0.25;
	echo $total_price = $apples * $price; 
	//This outputs 1.25
?>

Concatenation

Concatenation is essentially stitching two strings together. It can be done in single and double quotes by putting a full stop (.) between variables and/or strings

<?php
	$firstname = 'Mike';
	$lastname = 'Rotch';
	echo 'I love '.$firstname.' '.$lastname;
?>

Interpolation

Interpolation is outputting the variable from within a string and, unlike concatenation, it can only be done within double quotes (“). It’s best to use curly brackets ( {} ) around the variable although they’re not always needed.

<?php
	$firstname = 'Mike';
	$lastname = 'Rotch';
	$echo "I love {$firstname} {$lastname}"
?>
© Evan Smith 2009 - 2017