Home > database >  Set the value of a variable based on the value of another variable php
Set the value of a variable based on the value of another variable php

Time:11-05

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,

CodePudding user response:

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;
}
}

CodePudding user response:

Maybe $egg_type is null value. Therefore,you can improve your code (PHP 8.0 version) and set default value for b_num like this:

 $egg_type = $row["egg_type"] ;

 $b_num = match($egg_type) {
    'M/S Select Farm' => 1,
    'Free Range' => 1,
    'Barn' => 1,
    'Intensive' => 1,
    'Organic' => 1,
    'Brioche' => 1,
    default => 'nothing any value for b_num'

 };
                           
echo $b_num;
  • Related