Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Compiler Tools

PHP Data Types and Variables — string, int, bool

PHP Variables

Variables are "containers" for storing information. A variable can be used to hold values (eg. x=5) and expression (eg. z=x+y). PHP has no command for declaring a variable. We have to assign value to the PHP variable, while the creation of variable. If we want to create variable without assigning a value to it, then we assign NULL value to it. Generally in PHP, a variable does not need to be declared before adding a value to it.

Standard Rules for PHP Variable Names

  • Variable in PHP starts with a $ sign, followed by the name of the variable.
  • The variable name in PHP must begin with a alpha-numeric character or the underscore character i.e.(A-Z, a-z, 0-9, and underscore).
  • A variable name should not contain blank spaces.
  • A variable names are case sensitive i.e.($Y and $y are two different variable).

Scope of PHP Variables

Each variable has an area in which it exist, known as its scope PHP has four different variable scope:-

Local Scope:- A variable declared within a any PHP function is local and can only be accessed within that function.

example
<?php
    $X=5 //Global
	
	function myFun() {
		echo $X //Local
	}
	
	myFun();
?>

The above script will not give any output, because the echo statement refers to the local scope.

Key Takeaways
  • PHP is dynamically typed - variables automatically take the type of the value assigned.
  • Use gettype() to check a variable's type and settype() to convert it.
  • PHP has 8 primitive types: int, float, string, bool, array, object, null, and resource.
  • Variable names start with $ and are case-sensitive - \ and \ are different variables.
  • Use var_dump() for debugging - it shows both the type and value of a variable.
  • Type juggling (automatic type conversion) can cause unexpected behavior - use strict comparison (===) to avoid it.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.