1.2.48. 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.48.1. Suggestions

  • Make the callback first argument a reference

1.2.48.2. Specs

Short name

Structures/ArrayMapPassesByValue

Rulesets

All, Analyze, CE, CompatibilityPHP80, IsExt, IsPHP, IsStub

Exakat since

2.2.0

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Medium

Features

array, map, by-value, by-reference

Available in

Entreprise Edition, Community Edition, Exakat Cloud