Skip to content
Advertisement

How to Mange IF and Else In Forloop with Json empty Data

I am looking for

if { "name": "Morris Holmes", "occupation": "programmer", "country": "" }

When country”: “” string is empty on that time don’t run function because is not good for SEO. empty <td></td> td tag

How to manage if and else part

enter image description here

new.php

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <?php
    $data = file_get_contents('new.json');
    $key = json_decode($data);
    ?>

    <table>
        <tbody>
            <tr>
                <th>Name</th>
                <th>Occupation</th>
                <th>Country</th>
            </tr>

            <?php
            foreach ($key as $val) { ?>
                <tr>
                    <td> <?= $val->name; ?> </td>
                    <td> <?= $val->occupation; ?> </td>
                    <td> <?= $val->country; ?> </td>

                </tr>
            <?php
            }
            ?>
            <tr>

</body>

</html>
new.json
[
    { "name": "Manuella Navarro", "occupation": "teacher", "country": "Spain" },
    { "name": "Thomas Dawn", "occupation": "teacher", "country": "New Zealand" },
    { "name": "Morris Holmes", "occupation": "programmer", "country": "" }
]

Advertisement

Answer

Use following code

 if(!empty($val->country)){ <td> ... }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement