Compare positions of an array $ miarray [n]

0

How could I validate the values of the same array, that is, for example:

if ($miarray[0] < $miarray[1])
{
    //$miarray[0] toma el valor de $miarray[1]
}
if ($miarray[2] > $miarray[3])
{
    //$miarray[3] toma el valor de $miarray[2]
} 

//... etcétera...

But the thing is that I have $miarray[n] , and I do not know how to do it with n positions.

I was doing it with for , nothing else I did with 2 for to see how it worked.

for ($a=0; $a < count($miarray) ; $a++) 
{ 
    for ($b=0; $b < count($miarray); $b++) { 
        if($miarray[$a] > $miarray[$b])
        {
            $miarray[$b] = $miarray[$a];

        }
        else
        {
            $miarray[$a] = $miarray[$b];
        }
    }
}

Somewhere with these 2 for choose me the highest and change it, but put the highest value in all $miarray[] , and what I need is that only put the higher value between $miarray[0] and $miarray[1] , after verifying the highest between $miarray[2] and $miarray[3] , and so on ...

    
asked by Brayan Calderon 16.05.2017 в 16:58
source

2 answers

1

This code solves your problem:

for( $i = 0; $i <  count($miarray) - 1; $i++){

    if( $miarray[$i] < $miarray[$i + 1] ){
        $miarray[$i] = $miarray[$i + 1] ;
    }
    else{
        $miarray[$i + 1] = $miarray[$i] ;
    }

    i++;
    }
    
answered by 16.05.2017 в 17:34
0

There are already functions in php where you can order an array, the method will be called sort($myarray)

It also allows you to configure the sort, here I leave you the official information of php

link

Although you want to do it manually, on the internet you can search for "bubble method", "quicksort", etc. Which are sorting methods, if you search the internet for php I'm sure there will be some already done and well explained

    
answered by 16.05.2017 в 17:37