PHP Data Types

PHP supports several data types. Most common are: NULL, boolean, integer, float, string, array, object. Additionally, there are resource and callable types, and modern PHP adds union and nullable types.

TypeExamplesNotes
NULL$x = NULL;No value
Booleantrue, falseConditional logic
Integer1, -5, 0xFF, 0b1010Whole numbers
Float (double)3.14, 1.2e3Decimals / scientific
String"Hello", 'World'Text data
Array[10, 20], ["a"=>1]Ordered map (keys can be ints/strings)
Objectnew stdClass(), custom classesOOP instances
ResourceDB connection, file handleExternal system handles
Callablefunction(){}, [$obj,"method"]Can be invoked

Truthiness (What evaluates to false?)

ValueAs boolean
falseFalse
0, 0.0False
"" (empty string), "0"False
[] (empty array)False
NULLFalse
everything elseTrue

NULL

<?php
  $x = NULL;
  var_dump($x);  // NULL
  var_dump(isset($x)); // false
  var_dump(empty($x)); // true
?>

Booleans

<?php
  $isAdmin = true;
  if ($isAdmin) { echo "Welcome!"; }
?>

Integers & Floats

<?php
  $a = 10;
  $b = 3.14;
  $hex = 0xFF;
  $bin = 0b1010;
  var_dump($a, $b, $hex, $bin);
?>

Strings

Use single quotes for literal text, double quotes for interpolation/escapes.

<?php
  $name = "Sonu";
  echo 'Hello $name'; // Hello $name
  echo "Hello $name"; // Hello Sonu
?>

String Cheat-Sheet

FunctionExamplePurpose
strlen()strlen("Hello")Length
strpos()strpos("abc","b")Find position
substr()substr("abcdef",2,3)Slice
strtolower() / strtoupper()strtoupper("aBc")Case conversion
trim()trim(" hi ")Trim whitespace
str_replace()str_replace("cat","dog","catapult")Replace
explode() / implode()implode(", ", ["a","b"])String ↔ Array
sprintf()sprintf("Price: %.2f", 5.5)Formatted strings

HEREDOC / NOWDOC

<?php
  $name = "Sonu";
  $heredoc = <<<TXT
Hello $name
This is HEREDOC.
TXT;

  $nowdoc = <<<'TXT'
Hello $name
This is NOWDOC.
TXT;

  echo $heredoc;
  echo $nowdoc;
?>

Arrays

Indexed

<?php
  $nums = [10, 20, 30];
  echo $nums[1]; // 20
?>

Associative

<?php
  $user = [
    "name"=>"Sonu",
    "age"=>25
  ];
  echo $user["name"];
?>

Multidimensional

<?php
  $matrix = [[1,2],[3,4]];
  echo $matrix[1][0]; // 3
?>

Useful Array Functions

FunctionExamplePurpose
count()count($nums)Length
in_array()in_array(20,$nums)Contains?
array_push() / []$nums[] = 40Append
array_merge()array_merge($a,$b)Concatenate
array_keys() / array_values()array_keys($user)Keys/values
sort() / asort() / ksort()sort($nums)Sorting
array_map()array_map(fn($x)=>$x*2,$nums)Transform
array_filter()array_filter($nums,fn($x)=>$x>=20)Filter

Looping

<?php
  $user = ["name"=>"Sonu", "age"=>25];
  foreach ($user as $k => $v) {
    echo "$k: $v\n";
  }
?>

Objects (Quick Intro)

<?php
  class User {
    public $name;
    public $age;
    function __construct($name, $age) {
      $this->name = $name;
      $this->age  = $age;
    }
    function greet() {
      return "Hi, I'm {$this->name}, {$this->age} years old.";
    }
  }
  $u = new User("Sonu", 25);
  echo $u->greet();
?>

stdClass

<?php
  $obj = new stdClass();
  $obj->title = "Article";
  $obj->views = 100;
  var_dump($obj);
?>

Type Juggling & Casting

PHP automatically converts types where needed. You can also cast explicitly:

<?php
  $s = "25";
  $i = (int)$s;     // 25
  $f = (float)"3.14"; // 3.14
  $b = (bool)0;       // false
  var_dump($i, $f, $b);
?>

Strict Types & Type Declarations (PHP 7+ / 8+)

Use declare(strict_types=1); to force exact types for function parameters/returns in that file.

<?php
  declare(strict_types=1);

  function add(int $a, int $b) : int {
    return $a + $b;
  }
  echo add(2, 3);
?>

Union & Nullable Types (PHP 8+)

<?php
  function formatId(int|string $id) : string {
    return "ID: " . $id;
  }
  function findUser(int $id) : array|null {
    return null;
  }
?>

JSON (Strings ↔ Arrays/Objects)

<?php
  $arr = ["name"=>"Sonu", "age"=>25];
  $json = json_encode($arr);
  $back = json_decode($json, true); // assoc array
  var_dump($json, $back);
?>

Resources & Callables (Brief)

  • Resource: Special handle to external resources (DB connections, file pointers).
  • Callable: A function/method you can invoke (closures, [$obj,"method"], "strlen").

Practice Tasks

  1. Create an associative array of 3 users with name and age; loop and print only users aged ≥ 21.
  2. Write a function with declare(strict_types=1) that concatenates a string and an integer (cast the int).
  3. Take a JSON string of products; decode to an array, sort by price, print the cheapest product.
  4. Given $value from $_GET, show how it’s treated by empty() vs isset().
Next: Learn about Constants (define, const, magic constants) and then head to Operators.