I need to enter array values ​​based on a certain condition, what is the correct way to do this?

I have a forcycle that contains a condition (and an incremental value of i):

if(condition)){$arr[$i] = array("value" => $node->nodeValue));}
else{$arr[$i] = array("string" => $node->nodeValue);}

      

Eventually, I need to have an array like this:

    Array ( [1] => Array ( [string] => abc [value] => 0,999 ) 
            [2] => Array ( [string] => meh [value] => 0,123 ) 
            [x] => Array ( [string] => xxx [value] => xxx ) )

      

I realize my code is not working, I think I should be using array_push, but I was wondering if there is a better way to achieve this.

Many thanks

+1


a source to share


2 answers


Sorry, the question is not very clear. Is this what you are trying to do?



$result = array();
foreach( $nodes as $node ) 
{
    $type = 'value';
    if( is_string( $node->nodeValue ) )
    {
        $type = 'string';
    }

    $result[][$type] = $node->nodeValue;
}

      

+1


a source


You can write a little more concisely using the? Operator:



$fieldname = ($condition? "value" : "string"); 
$arr[$i][$fieldname] = $node->nodeValue ;

      

0


a source







All Articles