1

in this case i have 69 category item and i wanted to store each of the item by the category. so, my "IF and ELSEIF" statements will looks like this

    if ($category == 1){
       echo "1";
    } 
    elseif ($category == 2){
       echo "2";
    }
    elseif ($category == 3){
       echo "3";
    }
    elseif ($category == 4){
       echo "4";
    }

if i am keep with these way, this will takes lots of time. So is there any simple way to do this? Thank you

Rafal Kozlowski
  • 720
  • 5
  • 12

4 Answers4

1

Try for loop,

for($i=1;$i<70;$i++){
   if($category == $i){
      echo $i;
      break;
   } 
}
Vinod VT
  • 6,946
  • 11
  • 51
  • 75
1

use below way

$cat_arr = $result_arr_cat; // $result_arr_cat is result of category as associative
$arr_output = array('1'=>'1\'s output','2'=>'','3'=>''); // and so on
if(in_array($category,$cat_arr)){
 echo $category; // or keep the output in array of specific key echo $arr_output[$category];
}

Or even more simple

$arr_output = array(1=>'1\'s output', 2=>'', 3=>''); // and so on
if(array_key_exists($category, $arr_output)){
     echo $arr_output[$category];
}
Rafal Kozlowski
  • 720
  • 5
  • 12
AmmyTech
  • 738
  • 4
  • 10
0

Short solution using in_array and range functions:

if (in_array($category, range(1, 69))) {
    echo $category;
}
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

If you're just converting an integer to the equivalent string, use typecasting.

For example: echo (string)$category;

For more info, reference this answer: ToString() equivalent in PHP

Community
  • 1
  • 1
Jim Bergman
  • 5,207
  • 2
  • 17
  • 19