PHP's built-in functions can reduce repetitive code, but misreading a return value introduces new bugs. Distinguish validation from sanitization, and simple string splitting from CSV parsing. These examples use PHP 8.x syntax.
Transform each item with array_map
<?php
$numbers = [1, 2, 3];
$squares = array_map(fn($n) => $n * $n, $numbers);
echo json_encode($squares); // [1,4,9]
array_map produces a new array; it is not intended to remove elements. Returning null from the callback does not automatically remove that position. When passing several arrays, check length and key behavior separately. A straightforward loop may be easier to understand than a callback chosen only to save lines.
filter_var: distinguish false from zero
<?php
$value = filter_var('0', FILTER_VALIDATE_INT);
if ($value === false) {
echo 'Invalid';
} else {
echo 'Number: ' . $value; // Number: 0
}
A loose if (!$value) test can mistake valid zero for failure. FILTER_VALIDATE_EMAIL checks email syntax, not ownership. Sanitization filters may change input; the resulting value may no longer be the value the user intended to submit.
Do not apply trim to every field automatically
<?php
$input = " Hello ";
echo trim($input); // Hello
The default trim removes a particular set of whitespace and control characters at the ends, not every Unicode whitespace character. It leaves internal spaces intact. For passwords or text where spaces are meaningful, decide the field's rules instead of silently changing the value. Validate that request data is a string before passing it to trim.
Use explode for simple delimiters
<?php
$tags = explode(',', 'php,mysql,linux');
echo json_encode($tags); // ["php","mysql","linux"]
$line = '"Ankara, centre",42';
$fields = str_getcsv($line, ',', '"', '');
echo json_encode($fields); // ["Ankara, centre","42"]
Splitting a CSV row with explode breaks a quoted field containing a comma. Use a CSV parser; fgetcsv may be suitable when reading a file stream. Explicitly passing an empty escape parameter makes the intended behavior clear.
Include '0', an empty string, whitespace-only input, an unexpected array, and text containing delimiters in your test cases. Valid inputs should succeed, while invalid types should fail in a controlled way.
References: PHP documentation for filter_var, trim, and str_getcsv.
Related Articles