Search code examples
phpmysqlvariables

Set the value of a variable based on the value of another variable php


New to programming and looking for help please,

i need to the set the value of $b_num based on the value of $egg_type i have tried using an if statement but not having any luck

`

 $egg_type = $row["egg_type"] ;
                           
                          if ($egg_type == 'M/S Select Farm')
                          {
                             $b_num = '1';
                          }
                          
                           if ($egg_type = 'Free Range')
                          {
                             $b_num = '1';
                          }
                           
                           if ($egg_type = 'Barn')
                          {
                             $b_num = '2';
                          }
                          
                           if ($egg_type =='Intensive')
                          {
                             $b_num = '3';
                          }
                          
                          if ($egg_type == 'Organic')
                          {
                             $b_num = '0';
                          } 
                          if ($egg_type == 'Brioche')
                          {
                             $b_num = '3';
                          }

`

Tried the if statement but the value didnt change,


Solution

  • First you've to check if your $egg_type variable is being set in order not to make errors later Second you can do it like this

    if(isset($egg_type)) {
    if(in_array($egg_type, ['M/S Select Farm', 'Free Range'])) {
        $b_num = 1;
    } elseif(in_array($egg_type, ['Intensive', 'Brioche'])) {
        $b_num = 3;
    } elseif($egg_type === 'Organic') {
        $b_num = 0;
    } elseif($egg_type === 'Barn') {
        $b_num = 2;
    }
    }