php自己动手实现max,找出数组中最大的值

作者: 杨圣亮 分类: php开发 发布时间: 2018-10-26 01:26:12

php中对数组进行最大值输出,可以使用max()方法。然而,有时候,自己动手实现一次系统函数,也是一件愉快的事情,接下来我使用php代码来实现一个自定义函数:getMaxValue(array $arr)。该函数需要提供一个数组,程序就会返回数组中数值最大的那个数值。源码如下:

<?php
/**
 * Created by PhpStorm.
 * User: fedkey
 * Date: 18-10-26
 * Time: 下午12:17
 */

class ClassDemo
{
    public function getMaxValue(array $arr)
    {
        $maxValue = null;
        $indexLength = count($arr) - 1;
        //遍历数组$arr
        for ($a = 0; $a < $indexLength; $a++) {
            //索引号为$a的和索引号为 $a+1进行大小比较
            if ($arr[$a] >= $arr[$a + 1]) {
                //只有当$maxValue比$arr[$a]小时才改变$maxValue的值
                if ($maxValue < $arr[$a]) {
                    $maxValue = $arr[$a];
                }
            } else {
                if ($maxValue < $arr[$a + 1]) {
                    $maxValue = $arr[$a + 1];
                }

            }
        }
        return $maxValue;
    }
}

$demo = new ClassDemo();

echo $demo->getMaxValue([-9122, -10, -4, -9, -54, -6, -150, -2054, -32230, -33, -222, -55, -22, -10]);

输出结果:-4

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

8  ×  1  =  

微信