Example 1 — Build an Array from Variables
Collect two variables into one array.
<?php
$name = "Ann";
$age = 30;
$data = compact("name", "age");
echo json_encode($data), PHP_EOL; How It Works
- Create two ordinary variables, $name and $age.
- compact() looks up each variable by its name.
- It builds an array with the names as keys and the values as values.
- json_encode() prints the resulting array.

