Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print array in switch case with PHP

Tags:

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.

like image 883
Sz3jdii Avatar asked Jun 04 '26 16:06

Sz3jdii


1 Answers

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;
  }
}
like image 60
Oscargeek Avatar answered Jun 07 '26 09:06

Oscargeek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!