samuel toh
samuel toh

Reputation: 7076

How to displays the value of dynamic arrays?

My array is like this :

$a = array(
    array('CXLDay' => 8,
        'CXLRemark' => array(),
        'CXLFee'    =>150
    ),
    array('CXLDay' => 5,
        'CXLRemark' => array(),
        'CXLFee'    =>100
    ),
);

I display it using code like this :

foreach($a as $key=>$value)
{
    echo 'Day = '.$value['CXLDay'].', ';
    echo 'Fee = '.$value['CXLFee'].'<br>'; 
}

But, If my array change like this :

$a = array(
    'CXLDay' => 8,
    'CXLRemark' => array(),
    'CXLFee'    =>553191.010000
);

There exist error like this :

Notice: Undefined index: CXLDay...

Notice: Undefined index: CXLFee...

This seems necessary plus condition, but I'm still confused

How to displays the value of dynamic arrays?

Any help much appreciated

Upvotes: 0

Views: 41

Answers (2)

JanLeeYu
JanLeeYu

Reputation: 1001

You missed something in your code...

from

$a = array(
    'CXLDay' => 8,
    'CXLRemark' => array(),
    'CXLFee'    =>553191.010000
);

to

$a = array(
        array('CXLDay' => 8,
            'CXLRemark' => array(),
            'CXLFee'    =>553191.010000
        )
);

Upvotes: 0

Dan Walker
Dan Walker

Reputation: 453

The following code example would output both arrays in your example.

if(array_key_exists('CXLDay',$a)){
    echo 'Day = '.$a['CXLDay'].', ';
    echo 'Fee = '.$a['CXLFee'].'<br>'; 
}elseif(count($a) && array_key_exists('CXLDay',$a[0])){
    foreach($a as $key=>$value){
        echo 'Day = '.$value['CXLDay'].', ';
        echo 'Fee = '.$value['CXLFee'].'<br>'; 
    }
}

It would however always rely on the array key 'CXLDay' being present in the array.

Upvotes: 1

Related Questions