php 数组函数

自行实现 array_reverse

<?php

$arr = [
    "a" => 1,
    "c" => "cc",
    "d" => 2
];


function reverse($arr)
{
    $count = count($arr);
    $result = [];
    end($arr);
    for ($i = 1; $i <= $count; $i++) {
        $result[key($arr)] = current($arr);
        prev($arr);
    }
    return $result;
}

function reverse2($arr)
{
    $count = count($arr);
    $result = [];
    $keys = array_keys($arr);
    for ($i = 1; $i <= $count; $i++) {
        $key = $keys[$count-$i];
        $result[$key] = $arr[$key];
    }
    return $result;
}

var_dump(reverse($arr));
var_dump(reverse2($arr));

发表评论