Callbacks, JSON & Exceptions
A callback is a function passed to another function. array_map(), usort(), and array_filter() use callbacks often.
Callbacks
A callback is a function passed to another function. array_map(), usort(), and array_filter() use callbacks often.
Real-life example: A callback is giving a friend your phone number and saying "call me when dinner is ready."
<?php
$prices = [100, 200, 300];
$discounted = array_map(function ($p) {
return $p * 0.9;
}, $prices);
print_r($discounted);
// Named callback
function double(int $n): int { return $n * 2; }
$nums = array_map("double", [1, 2, 3]);
?>JSON — json_encode and json_decode
JSON is the standard data format for APIs. json_encode() turns PHP arrays into JSON strings. json_decode() parses JSON into arrays or objects.
Real-life example: JSON is a universal packing box — PHP, JavaScript, and mobile apps all understand the same label.
<?php
$user = ["name" => "Asha", "courses" => ["PHP", "MySQL"]];
$json = json_encode($user);
echo $json;
$parsed = json_decode($json, true); // true = associative array
echo $parsed["name"];
?>Exceptions
Use try { } catch (Exception $e) { } to handle errors gracefully. throw new Exception('message') signals failure.
Real-life example: Exceptions are fire alarms — normal work stops, you handle the problem, then continue safely.
<?php
function divide(int $a, int $b): float {
if ($b === 0) {
throw new InvalidArgumentException("Cannot divide by zero");
}
return $a / $b;
}
try {
echo divide(10, 2);
echo divide(10, 0);
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "\nDone.";
}
?>