Tomato
Tomato

Reputation: 779

If condition with array in Laravel

I'm trying to create an array to convert JSON. My data is queried from database. My problem is I have to check condition for array. If $item->verified == 1, my 'isVerified' will be true, my email will be in verified and opposite.

Here is what I did, I check condition and create 2 array for it. Can I just use 1 array for condition:

if( ($item->verified) == 1)
{
    $data[] = [
        'name'       => $item->fullname,
        'address'    => $item->address,
        'isVerified' => true,
        'email'      => [
            'verified'   => $item->email,
            'unverified' => []
        ]
    ];
}
else
{
    $data[] = [
        'name'       => $item->fullname,
        'address'    => $item->address,
        'isVerified' => false,
        'email'      => [
            'verified'   => [],
            'unverified' => $item->email
        ]
    ];
}

Upvotes: 0

Views: 2479

Answers (1)

Tharaka Dilshan
Tharaka Dilshan

Reputation: 4499

You can use ternary operator.

$data[] = [
    'name'       => $item->fullname,
    'address'    => $item->address,
    'isVerified' => $item->verified == 1,
    'email'      => [
        'verified'   => $item->verified == 1 ? $item->email : [],
        'unverified' => $item->verified == 0 ? $item->email : [],
    ]
];

Upvotes: 2

Related Questions