简体   繁体   中英

Print array in switch case with PHP

I'm trying to print diferent fields of $data array if they exist using switch/case.

Array ( [title] => title [type] => Movie [hour] => [dayoftheweek] => 5 [dayofthemonth] => )

What I'm trying to do:

<?php
switch($data):
    case 'title': 
        ?>
        <div class="col-md-4">
            <div class="name-value" id="title"><?=$data['title']?></div>
        </div>
        <?php
    break;
    case 'type': 
        ?>
        <div class="col-md-4">
            <div class="name-value" id="type"><?=$data['type']?></div>
        </div>
        <?php
    break;
endswitch;

Etc.

Thank you! The problem is nothing is beeing displayed but when I type for example <?=$data['type']?> outside switch/case it's displaying.

The problem is that your code are trying to use an array of multiples values like an unique variable.

You need to do a foreach to parse all array variables and then you can use a switch to get every value (title, type, etc..) and return the HTML that you need.

Try with this:

<?php 
/* Parse all values */
foreach ($data as $key => $value) {
  /* Parse all variables in each value */
  switch($key) {
    case 'title':
      ?>
        <div class="col-md-4">
          <div class="name-value" id="title"><?=$value?></div>
        </div>
      <?php
      break;
    case 'type':
      ?>
        <div class="col-md-4">
          <div class="name-value" id="type"><?=$value?></div>
        </div>
      <?php
      break;
  }
}

If the only qualifying criteria is a known set of keys, then you can filter out the elements that you don't want based on a white-list of keys. Then use a foreach loop to only echo white-listed data. If there are no qualifying elements, no echoes will be called.

Apparent advantages:

  • the whitelist array makes the solution very scalable in case you wish to adjust the data that you intend to display
  • pre-filtering the data means that the foreach loop never iterates data without displaying data.
  • the echoing lines are DRY (Don't Repeat Yourself); this keeps your code clean, concise, and easy to manage

Code: ( Demo )

$data = ['title' => 'The Title', 'type' => 'Movie', 'hour' => '', 'dayoftheweek' => 5, 'dayofthemonth' => ''];
$whitelist = ['title' => '', 'type' => ''];
$filtered = array_intersect_key($data, $whitelist);
// var_export($filtered);  // uncomment if you want to see what remains

foreach($filtered as $key => $value) {
    echo "<div class=\"col-md-4\">";
        echo "<div class=\"name-value\" id=\"$key\">$value</div>";
    echo "</div>";
}

Output:

<div class="col-md-4">
    <div class="name-value" id="title">The Title</div>
</div>
<div class="col-md-4">
    <div class="name-value" id="type">Movie</div>
</div>

This task can be achieved a number of ways depending on project requirements. You may even like to build in more filter conditions. If you want more certainty about what is the best technique, then you will need to offer more/better details about your project.


If you don't need a scalable solution, but you need to handle each key's data individually/differently, then you can write isset() calls and echo your content without any looping (iterated conditionals).

if (isset($data['title'])) {
    echo "<div class=\"col-md-6\">";
        echo "<div class=\"unique123\" id=\"movie_title\">{$data['title']}</div>";
    echo "</div>";
}
if (isset($data['type'])) {
    echo "<div class=\"col-md-4\">";
        echo "<div class=\"type_group\" id=\"type\">{$data['type']}</div>";
    echo "</div>";
}

In your case, working with PHP's foreach you have to check the current element's key, assigned to the $key variable on each iteration.

foreach (array_expression as $key => $value)
    statement

Also added some refactor to avoid duplicated code in your script.

Code example:

<?php 
foreach ($data as $key => $value) {
  if (in_array($key, ['title', 'type'])) {
    echo '<div class="col-md-4">';
      echo '<div class="name-value" id="' . $key . '">' . $value . '</div>';
    echo '</div>';
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM