Compare values of the following elements in an associative array

Asked 1 years ago, Updated 1 years ago, 40 views

$arr=['foo'=>10,'bar'=>11,'bazz'=>3,'fizz'=>8];

I would like to return false if the associative array is smaller than the value of the following elements.

php

2022-09-30 21:30

2 Answers

Here you are.
bool is_stairs(array$arg)

<?php
function get_numberic($value)
{
    if(!is_numeric($value)){
        through new InvalidArgumentException();
    }
    return$value+0;
}

function is_stairs(array$arg)
{
    if(!$arg){
        return false;
    }
    $stack=array_values($arg);
    $previ = array_shift($stack);
    $previ = get_numeric($previ);
    foreach($stack as$value){
        $value = get_numberic($value);
        if($value<$previ){
            return false;
        }
        $previ = $value;
    }
    return true;
}

It also supports normal arrangements.
An empty array returns false and an element returns true.
false does not return if the same value persists.
If the value contains an element where is_numeric returns false, InvalidArgumentException is issued.
I'm not sure, but it probably works with floating-point numbers.

<?php
// Empty array: bool(false)
var_dump(is_stairs([]));

// 1 element: bool(true)
var_dump(is_stairs([7]));

// bool(true)
var_dump(is_stairs([7,42]));

// Example: bool(false)
$arr=['foo'=>10, 'bar'=>11, 'bazz'=>3, 'fizz'=>8];
var_dump(is_stairs($arr)));

// bool(true)
$arr=['foo'=>0, 'bar'=>1, 'bazz'=>3, 'fizz'=>8];
var_dump(is_stairs($arr)));

// bool(true)
$arr=['foo'=>10, 'bar'=>11, 'bazz'=>13, 'fizz'=>18];
var_dump(is_stairs($arr)));

// bool(true)
$arr=['foo'=>-INF, 'bar'=>-11, 'bazz'=>3, 'fizz'=>8];
var_dump(is_stairs($arr)));


2022-09-30 21:30

<?php
$arr=['foo'=>10, 'bar'=>11, 'bazz'=>3, 'fizz'=>8];
// Get subscript list
$keys = array_keys($arr);
// Loops in current subscript order
for($n=0,$l=count($keys);($n+1)<$l;$n++){
    // If it is smaller than the following subscripts
    if($arr[$n]]<$arr[$n+1]]){
        // false indication
        echo"{$keys[$n]}<{$keys[$n+1]}:is false".nl2br(PHP_EOL);
    }
}


2022-09-30 21:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.