0

how to concatenate this syntax in controller using php. method 1 :

echo "<option '". if($p_main_cat_id==$value['main_cat_id']){echo 'selected';}."' value='".$value['main_cat_id']."'>".$value['name']."</option>";

//error is : unexpected if

Method 2:

echo "<option '".<?php if($p_main_cat_id==$value['main_cat_id']){echo 'selected';} ?>."' value='".$value['main_cat_id']."'>".$value['name']."</option>";

error is:

unexpected '<'

these both are giving error.please correct it. Thank you!

4 Answers4

0

You can't append a string to an if condition directly. Unless you are using Ternary Operator

You have to separate into several lines. Like:

Option 1

echo "<option selected='";
if( $p_main_cat_id==$value['main_cat_id'] ) echo 'selected';
echo  "' value='" . $value['main_cat_id'] . "'>" . $value['name'] . "</option>";

Option 2 Ternary Operator

echo "<option selected='" . ( $p_main_cat_id == $value['main_cat_id'] ? 'selected' : '' ) . "' value='".$value['main_cat_id']."'>".$value['name']."</option>";

Option 3

Or you can store the value on a variable and append it.

$isSelected = ""; //Init the variable with empty string. 
if( $p_main_cat_id == $value['main_cat_id'] ) $isSelected = 'selected'; //Use the condition here, if true, assign selected' to the variable

//You can now append the variable here
echo "<option selected='" . $isSelected . "' value='" . $value['main_cat_id'] . "'>" . $value['name'] . "</option>";
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

try ternary operator:

echo "<option ". $p_main_cat_id==$value['main_cat_id'] ? "selected": ""." value='".$value['main_cat_id']."'>".$value['name']."</option>";

Method 2:

$selected = $p_main_cat_id==$value['main_cat_id'] ? "selected": "";
echo "<option ". $selected." value='".$value['main_cat_id']."'>".$value['name']."</option>";
Bhaskar Jain
  • 1,651
  • 1
  • 12
  • 20
0

The most readable way is to set variables beforehand, then insert them into a double-quoted string:

extract($value);
$selected = $main_cat_id == $p_main_cat_id ? "selected" : "";
echo "<option $selected value='$main_cat_id'>$name</option>";
0

Here is a simple clean way to do that :

$option = '<option value="' . $value['main_cat_id'] . '" ';

// This is called a ternary operator and it basicaly means :
// If $p_main_cat_id == $value['main_cat_id'] is true then return 'selected >'
// Else return '>'
$option .= ($p_main_cat_id == $value['main_cat_id']) ? 'selected >' : '>';

$option .= $value['name'] . '</option>';

echo $option;
CryptoBird
  • 508
  • 1
  • 5
  • 22