0

I have a PHP script which interacts with my MySQL database. In my database I've got multiple columns, like:

'temp_0_state', 'temp_0_color', 'temp_1_state', 'temp_1_color', 'temp_2_state', 'temp_2_color' etc etc. till 'temp_50_state', 'temp_50_color'

All 50 records contain under the 'temp_xxx_state' a name or will be empty ("") and under 'temp_xxx_color' a color.

I can show all the colors of the 50 records manually, like

  if ($user['temp_0_state'] == "") {
  } else {
     echo . $user['temp_0_color'] . ;
     }
  if ($user['temp_1_state'] == "") {
  } else {
     echo . $user['temp_1_color'] . ;
     }
  if ($user['temp_2_state'] == "") {
  } else {
     echo . $user['temp_2_color'] . ;
     }

etc etc till

  if ($user['temp_50_state'] == "") {
  } else {
     echo . $user['temp_50_color'] . ;
     }

But it'll be easier, and to reduce the amount of php code, to use a foreach statement on the number in the middle of the column name for all records between 0 and 50 (0 < n < 50). How can I split the names and use a foreach statement on the number 0 till 50 between the underscores?

3
  • Dynamic column names doesn't seem like the best approach tbh; this feels like a workaround that could be avoided with a different database structure. Commented Jun 1, 2020 at 13:12
  • I was expecting this answer... Problem is, i'm using someone elses database and can't change anything to that. Commented Jun 1, 2020 at 13:19
  • I figured there might be a reason - which is why I only commented rather than attempted an answer ;) Commented Jun 1, 2020 at 13:24

2 Answers 2

1

I did not tested but you can give a try this:

for ($x = 0; $x <= 50; $x++) {

    $column = 'temp_'.$x.'_state';
    $color  = 'temp_'.$x.'_color';
    if ($user[$column] == "") {

    } else {
        echo $user[$color];
    }

}
Sign up to request clarification or add additional context in comments.

4 Comments

OP is using state and color columns
no, that works! But I had also some other features in the same code which I had to add.
You should update if ($user[$column] == "") { by the opposite condition if ($user[$column] != "") { so you don't need to write the else line.
@Dacobah you do not know if OP have or have not need for it. ..
0

A for statement would be more convenient in this situation, as you already know the maximum of records, according to your description:

for ($i = 0; $i <= 50; $i++) {
    if (!empty($user['temp_'.$i.'_state'])) {
        echo $user['temp_'.$i.'_color'];
    }
}

Please check the official for loop documentation to learn more about it: https://www.php.net/manual/en/control-structures.for.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.