如何用PHP 5.4实现等价JS函数?解决array_shift参数错误
Fixing the "array_shift() expects parameter 1 to be Array, null given" Error in Your PHP 5.4 Port
First, let's break down exactly what the original JavaScript code is doing—this is key to getting the PHP version right:
- We start with an array
itemholding a set of string values. - An immediately-invoked function (IIFE) takes the
itemarray and a count of 224. Inside this function:- The
fnfunction performs a left rotation on the array: it runsselected_imagetimes, each time shifting the first element off the start and pushing it to the end. - We call
fn(++count)— since count starts at 224, this means we do 225 full left rotations on the array.
- The
- Finally, the
$function takes an indexi, converts it to a number, and returns the element at that index in the modified array.
Correct PHP 5.4 Implementation
The error you're seeing almost certainly comes from not handling array references properly (PHP uses value-passing by default, unlike JavaScript which passes arrays/objects by reference). Here's the working equivalent code:
<?php // Initialize the original array matching the JS code $item = [ "footer", "__cpsExtensionHeader", "__cpsUrl", "__cpsPermalinkContainer", "setProperty", "translateY(-", "px)", "important", "style", "data---cpt", "fixed", "position", "auto", "transform", "translateY(", "transition" ]; // IIFE equivalent: pass $item by reference with & to modify the original array (function(&$params, $count) { $rotate = function($times) use (&$params) { // Run the rotation $times times while (--$times) { $shiftedElement = array_shift($params); array_push($params, $shiftedElement); } }; // Call rotation with ++$count (224 + 1 = 225 iterations) $rotate(++$count); })($item, 224); // Equivalent of the JS $ function to get elements by index $getItem = function($i) use ($item) { $index = (int)$i; // Match JS's implicit number conversion return $item[$index]; }; // Test it out (uncomment to see): // echo $getItem(0); ?>
Why Your Original Code Threw the Error
Here's the likely culprit in your initial PHP attempt:
- No reference passed to the function: In PHP, if you pass an array without
&, you're working with a copy. If your function tried to modify the original array but didn't use references, the variable inside the function might have become null (or the copy was discarded, leading to unexpected behavior). - Closure scope issue: PHP closures don't automatically inherit variables from the parent function scope. If you didn't use
use (&$params)in the inner rotation function, it wouldn't have access to the array at all, resulting in that null error when callingarray_shift().
By adding & to pass the array by reference and explicitly including the variable in the closure's use clause, we ensure the array stays accessible and modifications affect the original array, just like in the JavaScript code.
内容的提问来源于stack exchange,提问作者Bruno Andrade
相关产品推荐
相关产品推荐

