1.2.49. Array_Map() Passes By Value

array_map() requires the callback to receive elements by value. Unlike array_walk(), which accepts by value or by reference, depending on the action taken.

PHP 8.0 and more recent emits a Warning

<?php
// Example, courtery of Juliette Reinders Folmer
function trimNewlines(&$line, $key) {
    $line = str_replace(array("\n", "\r" ), '', $line);
}

$original = [
    "text\n\n",
    "text\n\r"
];

$array = $original;
array_walk($array, 'trimNewlines');

var_dump($array);

array_map('trimNewlines', $original, [0, 1]);

?>

See also array_map.

1.2.49.2. Connex PHP features

1.2.49.2.1. Suggestions

  • Make the callback first argument a reference

1.2.49.2.2. Specs

Short name

Structures/ArrayMapPassesByValue

Rulesets

All, Analyze, CE, Changed Behavior, CompatibilityPHP80

Exakat since

2.2.0

PHP Version

With PHP 8.0 and older

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Medium

Available in

Entreprise Edition, Community Edition, Exakat Cloud