Skip to content
Advertisement

How to sort an Array using If in PHP

I have the following Array which contains data such as: Card, Month and Year. However, I receive it in a disorganized way and I would like to treat these values to follow the pattern. No Card, Year and Month or Month, Card and Year. I tried to use the sort() functions of php, but without success!

Array                                                                                                                    (
[0] => Array 
(
    [0] => 5522 8600 0000 0000
    [1] => 2020
    [2] => 09
)

[1] => Array 
(
    [0] => 09
    [1] => 5522 8600 0000 0000
    [2] => 2020
)

[2] => Array 
(
    [0] => 5522 8600 0000 0000
    [1] => 20
    [2] => 9
)                                                                                                    
)

I would like to create a function in which the Array is organized as follows:

 Array                                                                                                                   (
    [0] => Array 
    (
        [0] => 5522 8600 0000 0000
        [1] => 09
        [2] => 2020
    )

    [1] => Array 
    (
        [0] => 5522 8600 0000 0000
        [1] => 09
        [2] => 2020
    )

    [2] => Array 
    (
        [0] => 5522 8600 0000 0000
        [1] => 9
        [2] => 20
    )
)

Then comes the point of conditions, if as the Array the year 2020 is defined with only 2 decimal places, that is, 20 (19, 20, 21, 22, 23, …) I would check if the value does not is greater than 12, following the number of months we have in 1 year, knowing this, to identify the year in this Array, I would apply another validation to check if the value is greater than 12 and if it has 2 or 4 digits, however I can’t apply it in any way!

Thank you very much in advance!

Advertisement

Answer

As per your comment you can go with this solution:

$finalArray = [];
foreach($array as $key=>$arr){
    $arry = [];
    foreach($arr as $ar){
        
        if(strlen($ar) > 4){
            $arry[0] = $ar;
        }else if((strlen($ar) ==1 || strlen($ar) == 2) && (int)$ar <=12){
            $arry[1] = $ar;
        }else{
            $arry[2] = $ar;
        }
    }
    ksort($arry);
    $finalArray[$key] = $arry;
}

print_r($finalArray);

Output: https://3v4l.org/BZIFX

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement