user3667492
user3667492

Reputation: 23

Boolean array in PHP

I have an one doubt with conditional array in php.

Here is my code,

foreach($orders as $order) {
array_push($list, array($order['name'],$order['email'],$order['buyer_accepts_marketing']));
}

Still now i got the value of $order['buyer_accepts_marketing'] is 1, but I want value as true.

I tried, but didn't get exact answer.

Can anyone help me? Thanks in advance!.

Upvotes: 1

Views: 5598

Answers (2)

Cully
Cully

Reputation: 6965

You can cast your value as boolean (c.f. http://www.php.net/manual/en/language.types.type-juggling.php):

foreach($orders as $order) {
    array_push($list, array(
        $order['name'],
        $order['email'],
        (boolean) $order['buyer_accepts_marketing']
    ));
}

Just FYI, a shortcut for array_push would be:

foreach($orders as $order) {
    $list[] = array(
        $order['name'],
        $order['email'],
        (boolean) $order['buyer_accepts_marketing']
    );
}

I generally find that it looks nicer :)

If you want to do more complex logic to get your boolean value you could create a new variable for it:

foreach($orders as $order) {
    $buyer_accepts_marketing = false;
    if( $order['buyer_accepts_marketing'] ) $buyer_accepts_marketing = true;

    array_push($list, array(
        $order['name'],
        $order['email'],
        $buyer_accepts_marketing
    ));
}

If you want to instead set your buyer_accepts_marketing value to a string value of "true" or "false", then do:

foreach($orders as $order) {
    $buyer_accepts_marketing = "false";
    if( $order['buyer_accepts_marketing'] ) $buyer_accepts_marketing = "true";

    array_push($list, array(
        $order['name'],
        $order['email'],
        $buyer_accepts_marketing
    ));
}

Just be aware that a string "true" is not boolean, nor is "false". For example:

if( "true" == true ) echo "It's true";

Will echo "It's true". However, so will:

if( "false" == true ) echo "It's true";

That's because any string that isn't set to "0" or "" will evaluate as true.

Upvotes: 2

railsbox
railsbox

Reputation: 888

You can simply use

foreach($orders as $order) {
if( $order['buyer_accepts_marketing'] ){ 
       $buyer_accepts_marketing = "true";
}
$list[] = array(
        $order['name'],
        $order['email'],
        $buyer_accepts_marketing; 
    );
}

Upvotes: 1

Related Questions