PHP Variables & Data Types – A Beginner’s Guide

What are Variables in PHP?

A variable in PHP is used to store data that can be used throughout a script. PHP variables are declared using the $symbol, followed by a name.

Declaring a Variable:

<?php
  $name = "John";
  echo "Hello, " . $name;
?>

Output:

Hello, John

Rules for Variable Names:

  • Must start with a $ sign.
  • Cannot start with a number (e.g., $1name is invalid).
  • Only letters, numbers, and underscores are allowed.
  • Case-sensitive ($Name and $name are different).

PHP Data Types

PHP supports several data types for storing different kinds of values.

1. String

A sequence of characters enclosed in quotes (" " or ' ').

<?php
  $greeting = "Welcome to PHP!";
  echo $greeting;
?>

2. Integer

Whole numbers (positive or negative).

<?php
  $age = 25;
  echo "Your age is " . $age;
?>

3. Float (Double)

Decimal numbers.

<?php
  $price = 19.99;
  echo "The price is $price";
?>

4. Boolean

Represents true or false values.

<?php
  $isLoggedIn = true;
  echo "Login status: " . $isLoggedIn;
?>

Output: Login status: 1 (true is displayed as 1, false as empty output)

5. Array

Stores multiple values in a single variable.

<?php
  $colors = array("Red", "Green", "Blue");
  echo $colors[0]; // Outputs: Red
?>

6. NULL

A variable with no value.

<?php
  $var = NULL;
  echo "Value: " . $var;
?>

Output: (Empty output)

7. Object (Advanced)

Used in Object-Oriented Programming (OOP).

Checking Variable Types

Use var_dump() to check a variable’s data type.

<?php
  $num = 42;
  var_dump($num);
?>

Output: int(42)

Type Casting

Convert one data type to another.

<?php
  $num = "10";
  $num = (int)$num;
  var_dump($num); // int(10)
?>

Summary

  • Variables store data and start with $.
  • PHP supports multiple data types like string, integer, float, boolean, array, and NULL.
  • Use var_dump() to check variable types.

Next Steps

Stay tuned for more PHP lessons!


Comments

Leave a Reply

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