Search code examples
phparraysif-statementranking

php IF statements inside `array()` function


I am trying to set an array based on query results that are NOT Null. In turn I hope to somehow create a ranking based on the NON Null results.

SQL Query returns:

Comp1    Comp2   Comp3   Comp4   Comp5   Comp6   Comp7   Comp8   Comp9
NULL     NULL    226.97   274    NULL    208     189     NULL    198.99

My PHP:

$COMP1 = $rankresult['Comp1'];
$COMP2 = $rankresult['Comp2'];
$COMP3 = $rankresult['Comp3'];
$COMP4 = $rankresult['Comp4'];
$COMP5 = $rankresult['Comp5'];
$COMP6 = $rankresult['Comp6'];
$COMP7 = $rankresult['Comp7'];
$COMP8 = $rankresult['Comp8'];
$COMP9 = $rankresult['Comp9'];

This does not work as I am trying to only put in variables that are NOT Null:

$myarray = 'array(
        if(!empty($COMP1)){ 
        $COMP1,}
        if(!empty($COMP2)){ 
        $COMP2,}
        if(!empty($COMP3)){ 
        $COMP3,}
        if(!empty($COMP4)){ 
        $COMP4,}
        if(!empty($COMP5)){ 
        $COMP5,}
        if(!empty($COMP6)){ 
        $COMP6,}
        if(!empty($COMP7)){ 
        $COMP7,}
        if(!empty($COMP8)){ 
        $COMP8,}
        if(!empty($COMP9)){ 
        $COMP9})';

Desired output:

$myarray = array(226.97,274,208,189,198.99)

Solution

  • Have you tried array_filter()?

    $result = array_filter($rankresult);
    

    Result:

    array(
        "comp3"=>226.97,
        "comp4"=>274,
        "comp6"=>208,
        "comp7"=>189,
        "comp9"=>198.99
    )