BAB 2: VARIABEL & TIPE DATA

2-4: String Interpolation

Objectives

  • Memahami perbedaan single quotes dan double quotes
  • Mengenal escape sequences
  • Menggunakan heredoc dan nowdoc
  • Memahami string concatenation

Single vs Double Quotes

Ini adalah konsep penting di PHP yang sering bikin bingung pemula.

AspekDouble Quotes "..."Single Quotes '...'
VariabelDiparse — "Halo $nama" menampilkan nilaiLiteral — 'Halo $nama' menampilkan $nama
Escape sequencesDiproses (\n, \t, dll)Hanya \\ dan \' yang diproses
KecepatanSedikit lebih lambat (negligible)Lebih cepat untuk string literal
Gunakan saatPerlu interpolation variabelString tanpa variabel / literal

Perbedaan Utama

php
<?php

$nama = "Andi";

// Double quotes - VARIABEL DIPARSE
echo "Halo, $nama";           // Halo, Andi
echo "Umur saya $umur";       // Umur saya 25 (jika $umur ada)

// Single quotes - LITERAL
echo 'Halo, $nama';           // Halo, $nama
echo 'Umur saya $umur';       // Umur saya $umur

?>

Variabel di dalam String

Simple Variable

php
<?php

$user = "Andi";

echo "Welcome, $user";       // ✅ Works
echo 'Welcome, $user';        // ❌ Shows literal $user

?>

Array Element

php
<?php

$users = ["Andi", "Budi", "Citra"];

echo "First user: $users[0]";        // First user: Andi
echo "Second user: {$users[1]}";     // Second user: Budi
echo "Last user: {$users[count($users)-1]}";  // Last user: Citra

// ⚠️ Tanpa braces, akan error atau hasil salah
// echo "$users[0]";     // Work (diperbolehkan)
// echo "$users0";       // ❌ PHP cari $users0 yang tidak ada!

?>

Object Property

php
<?php

class User {
    public $name = "Andi";
}

$user = new User();

echo "Hello, {$user->name}";    // Hello, Andi

// ⚠️ Tanpa braces
// echo "$user->name";   // Work (diperbolehkan)

?>

Complex Expressions

⚠️Perhatian

Complex (curly) syntax {$...} di dalam string hanya mendukung variabel, properti objek, dan array access — bukan ekspresi aritmatika. "{$a + $b}" akan menghasilkan parse error. Untuk menampilkan hasil operasi, gunakan concatenation.

php
<?php

$a = 5;
$b = 10;

// ✅ Benar: concatenation untuk ekspresi
echo "Sum: " . ($a + $b);      // Sum: 15
echo "Product: " . ($a * $b);  // Product: 50

// ❌ Salah: complex syntax tidak mendukung operasi aritmatika
// echo "Sum: {$a + $b}";  // Parse error!

// ✅ Array access tetap didukung dalam braces
$fruits = ["apple", "banana"];
echo "First: {$fruits[0]}";     // First: apple

// Array function dalam braces juga TIDAK valid
// echo "Count: {count($fruits)}";  // Parse error!
echo "Count: " . count($fruits);  // Count: 2

?>
💡Tip

Aturan praktis: di dalam "...", braces {} hanya untuk mengakses nilai (variabel {$var}, properti {$obj->prop}, array {$arr[0]}). Kalau kamu butuh memproses nilai (operasi, function call), keluarkan dari string dulu lalu gabung dengan . (concatenation).

Escape Sequences

Di Double Quotes

php
<?php

// Newline
echo "Baris 1\nBaris 2";

// Tab
echo "Kolom1\tKolom2\tKolom3";

// Backslash
echo "Path: C:\\xampp\\htdocs";

// Double quote
echo "Dia berkata: \"Halo semua!\"";

// Dollar sign (tampilkan literal $)
echo "Harga \$100";

// Unicode
echo "Unicode: \u{1F600}";  // Emoji 😀

?>

Di Single Quotes

php
<?php

// Hanya \\ dan \'
echo 'Path: C:\\xampp\\file';   // Path: C:\xampp\file
echo 'It\'s PHP';                // It's PHP
echo 'Garis miring: \\';         // Garis miring: \

// ⚠️ \n di single quotes TIDAK diproses jadi newline!
// echo 'Baris 1\nBaris 2';
// Output: Baris 1\nBaris 2 (literal!)

?>

Heredoc

Heredoc untuk string multiline dengan interpreted values.

php
<?php

$nama = "Andi";
$pekerjaan = "Developer";

$bio = <<<EOT
Informasi Personal:
-------------------
Nama: $nama
Pekerjaan: $pekerjaan
Skills: PHP, JavaScript, MySQL

Terima kasih!
EOT;

echo $bio;

/*
Output:
Informasi Personal:
-------------------
Nama: Andi
Pekerjaan: Developer
Skills: PHP, JavaScript, MySQL

Terima kasih!
*/

?>

Heredoc dengan Indentation

php
<?php

// ⚠️ Whitespace sebelum closing marker akan included!
$text = <<<EOT
Ini text.
  Ini ada indent.
EOT;
// Error jika ada whitespace sebelum EOT;

?>

Solusi untuk indentation:

php
<?php

// PHP 7.3+ - bisa indent closing marker
$text = <<<EOT
    Ini text dengan indent.
    Bisa rapi di code!
EOT;

// PHP < 7.3 - closing marker harus di column 0
$text = <<<EOT
Ini text.
EOT;

?>

Nowdoc

Nowdoc untuk string multiline yang literal (tidak diparse).

php
<?php

$nama = "Andi";

// Sekarang $nama TIDAK diparse
$sql = <<<'EOT'
SELECT * FROM users
WHERE name = '$nama'
AND status = 'active'
EOT;

echo $sql;

/*
Output:
SELECT * FROM users
WHERE name = '$nama'
AND status = 'active'
*/

?>

Perbandingan: Quotes vs Heredoc vs Nowdoc

php
<?php

$name = "Andi";

?>
MethodParsed?Multiline?Use Case
'single'Literal string
"double"String dengan variabel
<<<EOT (heredoc)Long text, SQL, HTML
<<<'EOT' (nowdoc)Code examples, literal text

String Concatenation

Operator . (dot) untuk menggabungkan string.

php
<?php

// Basic concatenation
$first = "Hello";
$last = "World";
$full = $first . " " . $last;
echo $full;  // Hello World

// Concatenation assignment
$text = "Hello";
$text .= " ";
$text .= "World";
echo $text;  // Hello World

// Multiple concatenations
$sql = "SELECT " . "id, " . "name " . "FROM users";
// SELECT id, name FROM users

?>

Concatenation vs Double Quotes

php
<?php

$first = "John";
$last = "Doe";

// Concatenation
$name1 = $first . " " . $last;

// Double quotes
$name2 = "$first $last";

// Keduanya output: "John Doe"

?>
💡Tip

Performance: Untuk string sederhana dengan variabel, double quotes lebih readable. Untuk operasi kompleks atau multiple concatenations, concatenation dengan . lebih jelas.

Common Patterns

1. Building HTML

php
<?php

$title = "Welcome";
$content = "Hello World";

$html = <<<HTML
<div class="container">
    <h1>{$title}</h1>
    <p>{$content}</p>
</div>
HTML;

?>

2. Building SQL

php
<?php

$table = "users";
$column = "name";
$value = "Andi";

// ❌ RENTAN SQL INJECTION - jangan lakukan ini di production!
$sql = "SELECT * FROM $table WHERE $column = '$value'";

// ✅ Menggunakan prepared statement (production safe)
$sql = <<<SQL
SELECT * FROM {$table}
WHERE {$column} = ?
SQL;

?>

3. Echo vs Print

php
<?php

// echo - lebih cepat, bisa multiple args
echo "Hello", " ", "World";   // Hello World

// print - return 1, hanya satu argumen
print "Hello World";           // Hello World

// Nilai return
$result = echo "text";  // ❌ Error - echo tidak return value
$result = print "text"; // ✅ 1 - print return 1

?>

Best Practices

  1. Gunakan double quotes untuk variabel interpolation

    • "Hello $name"
    • 'Hello ' . $name
  2. Gunakan single quotes untuk literal string

    • 'Hello World'
    • "Hello World"
  3. Gunakan heredoc untuk string panjang

    • <<<EOT ... EOT
  4. Escape special characters dengan backslash

    • "Harga \$100"
    • "Harga $100" (PHP coba parse $100!)
  5. Untuk SQL, selalu gunakan prepared statements

    • "SELECT * FROM users WHERE name = '$name'"
    • ✅ Prepared statement dengan ? placeholders

Common Mistakes

php
<?php

// ❌ ERROR: Undefined variable
echo "Hello $name";   // Notice: Undefined variable: name

// ✅ FIX: Check existence
echo "Hello " . ($name ?? "Guest");

// ❌ ERROR: Unexpected T_VARIABLE
// $sql = "SELECT * FROM users WHERE name = '$name's friends'";

// ✅ FIX: Escape atau gunakan nowdoc
$sql = "SELECT * FROM users WHERE name = '{$name}s friends'";

// ❌ ERROR: Confusing braces
// $users = ["Andi", "Budi"];
// echo "$users[0] and $users[1]'s friend";  // Parse error!

// ✅ FIX: Proper braces
echo "{$users[0]} and {$users[1]}'s friend";

?>

Exercise

  1. Prediksi output dari:

    php
    $a = "Hello";
    $b = 'Hello';
    var_dump($a === $b);  // ?
    
  2. Buat string multiline menggunakan heredoc yang berisi:

    • Header dengan variabel $title
    • List items dengan array loop
    • Footer dengan $date
  3. Apa perbedaan output dari:

    php
    echo "\$100";    // vs
    echo '$100';
    
  4. Buat HTML card dengan heredoc:

    php
    $card = <<<HTML
    <div class="card">
        <h2>{$title}</h2>
        <p>{$description}</p>
    </div>
    HTML;
    

Summary

KonsepPenjelasan
Single quotesLiteral, hanya \\ dan \' diproses
Double quotesInterpreted, variabel & escape sequences diproses
HeredocMultiline, interpreted, <<<EOT
NowdocMultiline, literal, <<<'EOT'
Concatenation. operator untuk gabung string
Braces {}Untuk complex variable expressions

💡Tip

Gunakan single quotes untuk string tanpa variabel — lebih cepat dan signals intent bahwa string adalah literal. Gunakan double quotes hanya ketika kamu benar-benar butuh interpolation.

Klik tombol ini setelah menyelesaikan materi

📝

Quiz Bab 2

Uji pemahamanmu tentang Variabel & Tipe Data