user580950 user580950 - 1 year ago 40
PHP Question

PHP Fatal error: Trying to compare `if ($row['distance_name']==$split($i)`

I am trying to compare $split variable deinfed at top of the php code($split1, $split2) with database record

if ($row['distance_name']==$split($i)

and it throws error
PHP Fatal error: Function name must be a string


$plan_sql="select distance_name from mytablename";

while ($row=mysqli_fetch_array($plan_res, MYSQLI_ASSOC)) {

$result[] = $row;

for ($i=1; $i <= 8; $i++):?>
<div class="form-group">
<label>Split <?php echo $i; ?></label>
<select class="form-control required" name='distance[]' id='distance' >
<option value="">Select Distance</option>
<?php foreach ($result as $row):?>
<option value="<?php echo $row['distance_name'];?>" <?php if ($row['distance_name']==$split($i)) echo ' selected="selected"'; ?>><?php echo $row['distance_name'];?></option>
<?php endforeach ?>
<?php endfor; ?>

Answer Source

You're trying to use a "variable variable" - which is not usually the best way to do things - and doing it incorrectly. $split($i) doesn't mean "the variable named 'split and the value of $i.'" It means, "take a variable named $split, treat it as a function, and call that function with a parameter of $i."

If you really want to use variable variables, your syntax needs to be this:

${'split' . $i}

Again, this is a bad idea. You really should use an array instead.