WeCodeAcademy

PHP Exceptions and JSON

ExamplePHP
<?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, 4), "\n";
  echo divide(1, 0), "\n";
} catch (InvalidArgumentException $e) {
  echo "Error: ", $e->getMessage(), "\n";
} finally {
  echo "done\n";
}

$json = '{"name":"Ada","skills":["math","code"]}';
$data = json_decode($json, true);
echo $data["skills"][1], "\n";
echo json_encode(["ok" => true, "count" => 3]), "\n";
Output
2.5
Error: Cannot divide by zero
done
code
{"ok":true,"count":3}
Quick check

Which function turns a JSON string into a PHP array?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.