Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

second largest absolute value form array in php

second largest absolute value form array

input : array(13, -12, 8, 2, 5)

expected answer : 12

here is my code

<?php
function print2largest($arr, $arr_size)
{
    if ($arr_size < 2)
    {
        echo(" Invalid Input ");
        return;
    }     
    $first = $second = PHP_INT_MIN;
    for ($i = 0; $i < $arr_size ; $i++)
    {
        if ($arr[$i] > $first)
        {
            $second = $first;
            $first = $arr[$i];
        }

        else if ($arr[$i] > $second &&
                 $arr[$i] != $first)
            $second = $arr[$i];
    }
    if ($second == PHP_INT_MIN)
        echo("There is no second largest element\n");
    else
        echo("The second largest element is " . $second . "\n");
}     
$arr = array(13, -12, 8, 2, 5);
$n = sizeof($arr);
print2largest($arr, $n);
?>

output i got : 8

like image 327
Uzair Kapadia Avatar asked Dec 05 '22 11:12

Uzair Kapadia


2 Answers

It can be easy done in "php-way":

$arr = array(13, -12, 8, 2, 5);
$absoluteArr = array_map('abs', array_unique($arr));
rsort($absoluteArr);
echo $absoluteArr[1];
like image 103
brevis Avatar answered Dec 25 '22 13:12

brevis


No need to do that much code, do directly:

<?php

    $array  = array(13, -12, 8, 2, 5);
    $final_array = array_unique(array_map('abs',$array)); // remove duplicates and apply abs() to all elements
    rsort($final_array,SORT_NUMERIC); //reverse sort array numerically

    echo $final_array[1]; //get second highest

Output:-https://3v4l.org/mgjaO

Reference:-

abs()

array_map()

array_unique()

rsort()

like image 29
Anant Kumar Singh Avatar answered Dec 25 '22 13:12

Anant Kumar Singh