Values, types and array keys
Choose strict comparisons and predictable array shapes before transforming data.
A value has a type
PHP can coerce values during loose comparison. A form field containing the string '7' and an integer 7 may compare equal with == even though they arrived through different paths. Use === when identity of the value and type matters, especially for identifiers and validation. Convert at a trusted boundary, then work with the normalized type.
Arrays have keys
A PHP array can behave as a list or a map. Filtering and de-duplication preserve original keys, so the result may no longer be a zero-based list. Call array_values when a consumer expects a list; keep keys when they carry meaning.
$items = [3, 1, 3, 2];
$unique = array_values(array_unique($items)); // [3, 1, 2]
Trace a boundary case
Suppose an API accepts tags and later returns them as JSON. First validate that the input is a list of strings. Then trim and filter empty values, de-duplicate according to an explicit rule, and reindex. Decide whether 'PHP' and 'php' are the same tag before choosing a comparison strategy. A test should cover empty input, repeated tags, mixed case, and numeric-looking strings.
$tags = array_values(array_filter(array_map('trim', $tags), fn ($tag) => $tag !== ''));
Avoid accidental equality
array_unique with its default string comparison and SORT_REGULAR can make different values appear equal in surprising ways. If types matter, build a key that includes the type; if case-insensitive text matters, normalize text first. Write down the equality rule in the function name or documentation. This prevents a helper that works for integers from silently changing product behavior for names or identifiers.
Check your understanding
Why can an array returned by array_filter need array_values before JSON encoding?
Show explanation
array_filter preserves numeric keys. Gaps can make JSON encode the array as an object; array_values reindexes it as a list.
You can read for free. Create an account to save your progress.
Next lesson: Validate a request at its boundary →Put this lesson into practice
A practice activity at this level in the same module.
Try: Create a URL-safe slugFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.