frobak frobak - 4 months ago 9
PHP Question

PHP in_array and concatenate

I'm trying to use in_array concatenated in a bootstrap label to determine if its checked or not, but its not working.

This works and echo's 'active' so I know in theory its producing the correct results, but I cant get it to work within my loop

echo "<td>";
echo (in_array($course->course_id, $assign_data))?'active':'';
echo "</td>";


But this wont work and it echoes 'active' outside of the table and breaks up the html

foreach($course_data as $course){
echo "<tr>";
echo "<td data-title='Course Name'>" . $course->course_name . "</td>";
echo "<td data-title='Icon' class='text-center'><i class='fa fa-lg brand " . $course->course_icon . "' ></i></td>";
echo "<td data-title='Renewal Period'>" . $course->renewal_period . " Months</td>";
echo "<td data-title='Assign'>
<div class='btn-group' data-toggle='buttons'>
<label class='btn btn-default btn-sm' " . (!in_array($course->course_id, $assign_data))?' active':'' . ">
<input type='radio' name='course[" . $course->course_id . "]' value='No' autocomplete='off' > No
</label>
<label class='btn btn-default btn-sm' " . (in_array($course->course_id, $assign_data))?' active':'' . ">
<input type='radio' name='course[" . $course->course_id . "]' value='Yes' autocomplete='off' > Yes
</label>
</div>
</td>";
echo "</tr>";
}


Cant i use in_array concatenated like this?

Answer

You should ensure you're properly formatting output strings when mixing HTML and PHP:

Note: I prefer this syntax instead of echos since it allows HTML highlighting in my IDE

foreach($course_data as $course){               
    echo "<tr>";                                                    
        echo "<td data-title='Course Name'>" . $course->course_name . "</td>";
        echo "<td data-title='Icon' class='text-center'><i class='fa fa-lg brand " . $course->course_icon . "' ></i></td>";                                                             
        echo "<td data-title='Renewal Period'>" . $course->renewal_period . " Months</td>";
        echo "<td data-title='Assign'>
                <div class='btn-group' data-toggle='buttons'>
                    <label class='btn btn-default btn-sm" . (!in_array($course->course_id, $assign_data))?' active':'' ) . "'>
                        <input type='radio' name='course[" . $course->course_id . "]' value='No' autocomplete='off' > No
                    </label>
                    <label class='btn btn-default btn-sm" . (in_array($course->course_id, $assign_data))?' active':'') . "'>
                        <input type='radio' name='course[" . $course->course_id . "]' value='Yes' autocomplete='off' > Yes
                    </label>
                </div>                                                              
            </td>"; 
    echo "</tr>";                       
}