if statement in while loop

I have a PHP script that gets some data from a table in my MySQL database. And then it sends this information back to the PHP page with JSON javascript.

It all works great but i would like to make an if statement in the while loop. My "used" table sends back "1" and "5" instead of echoing back 1 or 5 i want it to send Yes or NO.

One way of doing this could be breaking down the $data and replace the 1 or 5 with Yes or No. But is there any another way of doing it?

Something like: `if (used == '1') { set used == 'No } else {set used == 'Yes' }`

my code below

 while ($row = $result->fetch_assoc()) {
    $data['results'][] = array(
        'id' => $row['id'],
        'number' => $row['number'],
        'type' => $row['type'],
        'code' => $row['code'],
        'price' => $row['price'],
        'used' => $row['used'],
        'utime' => $row['utime'],
        'username' => $row['username']
    );
}
//Everything went to plan so set success to true
$data['success'] = true;

//Set the content type for a json object and ensure charset is UTF-8. NOt utf8 otherwise it will not work in IE (Darn IE! >.<)
header("Content-Type: application/json; charset=UTF-8");

//json encode the data and cast to an object so we can reference items like this.id in the javascript instead of this['id'] etc.
echo json_encode((object)$data);

Upvotes: 0

Views: 126

Answers (2)

ofca
ofca

Reputation: 661

You can do this without if statement:

$answer = array(0 => 'No', 1 => 'Yes');

...
'used' => $answer[ $row['used'] ],
...

Upvotes: 0

Barmar
Barmar

Reputation: 780787

You can use the conditional operator in the array assignment:

'used' => $row['used'] == 1 ? 'Yes' : 'No',

Upvotes: 3

Related Questions