BAB 2: VARIABEL & TIPE DATA

2-2: Tipe Data

Objectives

  • Mengenal 5 tipe data primitive di PHP
  • Memahami type juggling (automatic conversion)
  • Menggunakan explicit type casting
  • Memahami type checking functions

5 Tipe Data Primitive di PHP

#TipeContohPenjelasan
1string"Hello", 'World'Sequence of characters / teks
2int1, 42, -5Bilangan bulat
3float3.14, -0.5Bilangan desimal
4booltrue, falseNilai kebenaran
5nullnullTidak punya nilai

1. String

String adalah sequence of characters, digunakan untuk menyimpan teks.

php
<?php

// Single quotes - literal string
$nama = 'Andi';

// Double quotes - interpreted string (bisa pakai variabel)
$salam = "Halo, $nama";  // Output: Halo, Andi

// Heredoc - untuk string multiline
$bio = <<<EOT
Nama saya $nama.
Saya adalah developer PHP.
Saat ini tinggal di Jakarta.
EOT;

// Nowdoc - literal multiline
$sql = <<<'EOT'
SELECT * FROM users
WHERE status = 'active'
ORDER BY created_at DESC
EOT;

?>

2. Integer

Integer adalah bilangan bulat (tanpa desimal).

php
<?php

$umur = 25;
$negatif = -10;
$hex = 0xFF;       // 255 (hexadecimal)
$octal = 0755;     // 493 (octal)
$binary = 0b1010;  // 10 (binary)

echo $umur;      // 25
echo $hex;       // 255
echo PHP_EOL;
echo $octal;     // 493
echo $binary;    // 10

// Integer overflow (32-bit vs 64-bit)
echo PHP_INT_SIZE;    // 8 (bytes) di 64-bit
echo PHP_INT_MAX;    // 9223372036854775807
echo PHP_INT_MIN;    // -9223372036854775808

?>

3. Float (Double)

Float adalah bilangan desimal.

php
<?php

$harga = 19.99;
$pi = 3.14159;
$scientific = 1.2e3;    // 1200
$negative = -273.15;

echo $harga;        // 19.99
echo $pi;           // 3.14159
echo $scientific;   // 1200

// Precision issue
$a = 0.1;
$b = 0.2;
$c = $a + $b;

// ⚠️ Output: 0.30000000000000004 (floating point precision)
echo $c;

// ✅ Solusi: gunakan integer untuk kalkulasi uang
// Simpan sebagai sen (integer): 1999 sen, bukan 19.99
$harga_sen = 1999;
$pajak_sen = 200;  // 2.00
$total_sen = $harga_sen + $pajak_sen;
echo $total_sen / 100;  // 21.99

?>
⚠️Perhatian

Floating Point Precision Issue: Jangan pernah gunakan float untuk perbandingan langsung pada kalkulasi finansial/money. Gunakan integer (sen/cent) atau library khusus seperti brick/money.

4. Boolean

Boolean hanya punya dua nilai: true atau false.

php
<?php

$is_active = true;
$is_empty = false;

// Truthy values (dianggap true dalam kondisi)
if ("non-empty string") echo "1. String non-empty → true";
if (42) echo "2. Non-zero number → true";
if ([1, 2]) echo "3. Non-empty array → true";
if (1.0) echo "4. Non-zero float → true";

// Falsy values (dianggap false dalam kondisi)
if ("") echo "TIDAK";       // Empty string → false
if (0) echo "TIDAK";        // Zero → false
if (0.0) echo "TIDAK";     // Zero float → false
if ([]) echo "TIDAK";       // Empty array → false
if (null) echo "TIDAK";     // Null → false
if ("0") echo "TIDAK";      // String "0" → false

?>

5. NULL

NULL merepresentasikan variabel tanpa nilai.

php
<?php

$belum_diisi = null;

// Cek null
if (is_null($belum_diisi)) {
    echo "Variabel ini null";
}

// Non-null assignment
$belum_diisi = "Sekarang ada isinya";
echo $belum_diisi;

// null vs unset
$var1 = "hello";
unset($var1);       // Variabel dihapus sepenuhnya
// echo $var1;        // Error: undefined variable

$var2 = null;       // Variabel tetap ada, nilainya null
var_dump($var2);     // NULL

?>

Type Juggling (Automatic Conversion)

PHP secara otomatis mengkonversi tipe data sesuai konteks.

php
<?php

// String + Integer → String concatenated
$text = "Umur: " . 25;           // "Umur: 25"

// String + Float → String concatenated
$text = "Harga: " . 19.99;      // "Harga: 19.99"

// String number + Integer operation
$num_str = "5";
$result = $num_str * 2;          // 10 (string dikonversi ke int)

// Boolean dalam string
$result = "text" . true;         // "text1"
$result = "text" . false;       // "text"

// ⚠️ Tricky cases
$value = "10 apples";
$result = $value * 2;           // 20 (string dipotong di awal angka)
                                // PHP ambil "10", buang " apples"

$value = "apples 10";
$result = $value * 2;           // 0 (tidak ada angka di awal)

?>

Explicit Type Casting

Konversi tipe secara manual.

php
<?php

$angka = 42;
$string = "99 bottles";

// Integer → String
$str = (string) $angka;
echo $str;              // "42"
echo gettype($str);     // string

// String → Integer
$num = (int) $string;
echo $num;              // 99
echo gettype($num);     // integer

// Float → Integer (floor)
$price = 19.99;
$whole = (int) $price;
echo $whole;            // 19 (dibulatkan ke bawah)

// String → Float
$value = "3.14";
$f = (float) $value;
echo $f;                // 3.14

// Boolean → String
$active = true;
echo (string) $active;  // "1"
$active = false;
echo (string) $active;  // "" (empty string)

// Array ↔ String
$arr = (array) "hello"; // ["hello"]
$str = (string) ["a"];  // "Array" (warning!)

?>

Type Checking Functions

php
<?php

$nilai = 85;
$nama = "Andi";
$harga = 19.99;
$aktif = true;
$data = null;
$items = ["a", "b"];

// is_int() / is_integer()
is_int($nilai);        // true
is_integer($nilai);    // true (alias)
is_int($nama);         // false

// is_string()
is_string($nama);      // true
is_string($nilai);     // false

// is_float() / is_double()
is_float($harga);      // true
is_double($harga);     // true (alias)

// is_bool()
is_bool($aktif);       // true

// is_null()
is_null($data);        // true

// is_array()
is_array($items);      // true
is_array($nama);       // false

// is_numeric()
is_numeric("42");      // true
is_numeric("3.14");    // true
is_numeric("42x");     // false

// is_scalar() - primitive types
is_scalar($nilai);     // true
is_scalar($items);      // false (array)

// gettype() - returns type as string
echo gettype($nilai);  // "integer"
echo gettype($nama);    // "string"

?>

Type Declaration (PHP 7+)

Batasi tipe parameter dan return value.

php
<?php

// Parameter type declaration
function greet(string $name): string {
    return "Hello, $name!";
}

echo greet("Andi");      // "Hello, Andi!"
echo greet(123);         // TypeError! (PHP 7+)

// Return type declaration
function add(int $a, int $b): int {
    return $a + $b;
}

echo add(5, 3);          // 8

// Float return
function divide(int $a, int $b): float {
    return $a / $b;
}

echo divide(10, 4);      // 2.5

// Nullable return (PHP 7.1+)
function findUser(int $id): ?string {
    if ($id === 1) {
        return "Andi";
    }
    return null;  // bisa return null
}

// Union types (PHP 8.0+)
function process(int|float $value): int|float {
    return $value * 2;
}

?>

Type Comparison Table

php
<?php

// Loose comparison (==)
$a = 0;
$b = "0";
$c = false;
$d = null;

var_dump($a == $b);  // true  (nilai sama, type berbeda)
var_dump($a == $c);  // true  (0 == false)
var_dump($a == $d);  // true  (0 == null)

// Strict comparison (===)
var_dump($a === $b); // false (type berbeda)
var_dump($a === $c); // false (type berbeda)
var_dump($a === $d); // false (type berbeda)

?>
Perbandingan=====
0 == "0"truefalse
0 == falsetruefalse
0 == nulltruefalse
"" == falsetruefalse
"0" === "0"truetrue
💡Tip

Best Practice: Selalu gunakan === untuk perbandingan unless kamu explicitly bermaksud membandingkan nilai dengan type coercion.

Exercise

  1. Identifikasi tipe data dari value berikut:

    • "Hello World"
    • 42
    • 3.14159
    • true
    • null
    • "42"
  2. Apa output dari:

    php
    echo (int) "123 hello";  // ?
    echo (int) "hello 123";  // ?
    
  3. Buat function addVAT(float $price): float yang menambahkan 11% VAT.

  4. Apa bedanya is_null($var) dan $var === null?

Summary

TipeContohFungsi
String"text", 'text'Teks
Integer42, -5, 0xFFBilangan bulat
Float3.14, -0.5Bilangan desimal
Booleantrue, falseKondisi
NULLnullTidak ada nilai
KonsepPenjelasan
Type jugglingPHP otomatis konversi tipe
Type castingKonversi manual (int)$var
Type checkingis_int(), is_string(), dll
Type declarationfunction foo(int $x)

💡Tip

Kata "juggling" dalam programming bukan berasal dari act of juggling balls, tapi dari circus performers yang continuously convert/change objects in the air. Type juggling berarti PHP continuously converts types based on context!

Klik tombol ini setelah menyelesaikan materi

📝

Quiz Bab 2

Uji pemahamanmu tentang Variabel & Tipe Data