improve php function, keeping list/each loop style: // d: position an element next to…
- User
improve php function, keeping list/each loop style:
// d: position an element next to another in an array // i: array item element // i: mix array,prev) { if ( !is_array(array); while ( list(v)=each(out[]=v==out[]=out; }
Assistant
Here's an improved version of the
item_reg_next_tofunction, keeping the list/each loop style:phpfunction item_reg_next_to($array, $item, $prev) { if (!is_array($array)) { return false; } $out = []; $found = false; reset($array); while (list($k, $v) = each($array)) { $out[] = $v; if ($v == $prev) { $out[] = $item; $found = true; } } if (!$found) { $out[] = $item; } return $out; }Here's what I've changed:
- I added a
$foundflag to keep track of whether the$prevelement was found in the array. This is used to determine whether to add the$itemelement at the end of the array if it wasn't found next to the$prevelement. - I moved the addition of the
$itemelement to a separate statement, so that it's only added if the element was found.
- I added a