2

I want to use for loop inside echo statement and I have used following code but its getting error can anyone please help me?

$a = "<select class='formfield_select'   name='return_pickuptime_hh' id='rhh' disabled='disabled'>
                      <option value='' selected='selected' disabled='disabled'>Hour</option>
                      ".for($i=$data['timeh'];$i <= 24;$i++) {."
                      <option value='".$i."'>".$i."</option>
                      ". } ."
                    </select>"; 

This code is in ajax part so i need this whole html as one variable so that i can replace this part The error is like this syntax error, unexpected T_FOR in CI/application/controllers/lha.php on line 748

7
  • syntax error, unexpected T_FOR in CI/application/controllers/lha.php on line 748
    – chirag
    Nov 9, 2013 at 6:15
  • 2
    that error is because a for loop is not meant to be appended to an string
    – Joe
    Nov 9, 2013 at 6:19
  • see the below answer its work Nov 9, 2013 at 6:21
  • for loop in echo its not possible...you have to change it Nov 9, 2013 at 6:22
  • 1
    Any good reason to use for loop in a echo ? PHP : how to use foreach loop inside an echo statement?
    – Uours
    Nov 9, 2013 at 6:22

2 Answers 2

11

id recommend either building your options first then appending them to your echo string like so:

$optionString = '';
for ( $i = $data['timeh']; $i <=24; $i++ ){
 $optionString .= "<option ...>".$i."</option>";
}

or making 2 echos to open and close the select and a loop with the option echo in the middle eg

echo "<select ...>";

for ( $i = $data['timeh']; $i <=24; $i++ ){
 echo "<option ...>".$i."</option>";
}

echo "</select>"; 
3
  • sorry but i need this html part in one variable
    – chirag
    Nov 9, 2013 at 6:22
  • then i would set a variable like $htmlString... set it to your opening select string. use the above for loop to append the options. after the loop append the closing select tag - and echo it all out at once
    – Joe
    Nov 9, 2013 at 6:25
  • 1
    @chirag Then replace the first echo with $string=, and the remaining ones with $string.=. Then $string will contain everything in one variable, which can be echo'd. Nov 9, 2013 at 6:25
0

try this..

echo "<select class='formfield_select'   name='return_pickuptime_hh' id='rhh' >
                  <option value='' selected='selected' >Hour</option>
                  ";


                  for($i=0;$i<=24;$i++) 
                  {

                  echo "<option value=$i>$i</option>";

                   } 

                echo "</select>"; 
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.