How to split comma-separated values from database in CodeIgniter

I’m working with a database table named user_preferences that stores information about user property searches. The table has columns like user_id, budget_min, budget_max, and home_type. The home_type column contains comma-separated values like “Apartment,Condo,Townhouse”.

Here’s my model function that retrieves the data:

public function getUserPreferences($userId)
{
    $result = $this->db->get_where('user_preferences', array('user_id' => $userId));
    return $result->row();
}

In my controller, I’m calling this function:

$data['userInfo'] = $this->preference_model->getUserPreferences($userId);
$this->layout->view('admin/users/edit_preferences', $data);

I want to split the comma-separated home_type values in the controller so I can pre-select the appropriate checkboxes in my view. My view has checkboxes like this:

<label>
    <input type="checkbox" value="apartment" name="hometype[]">
    Apartment
</label>
<label>
    <input type="checkbox" value="condo" name="hometype[]">
    Condo
</label>
<label>
    <input type="checkbox" value="townhouse" name="hometype[]">
    Townhouse
</label>

How can I explode the comma-separated values and pass them to my view so the checkboxes get pre-selected based on the database values?

Your controller approach is right, but you need to fix the case-sensitivity issue between your database values and checkbox values. After exploding the comma-separated string, convert everything to lowercase for comparison. In your controller, add this after getting the user preferences: php $homeTypes = !empty($data['userInfo']->home_type) ? explode(',', $data['userInfo']->home_type) : array(); $data['selected_home_types'] = array_map('strtolower', array_map('trim', $homeTypes)); The trim() removes whitespace around values - important since comma-separated data usually has spaces. In your view, use the checked attribute conditionally: html <input type="checkbox" value="apartment" name="hometype[]" <?php echo in_array('apartment', $selected_home_types) ? 'checked' : ''; ?>> This way your checkboxes get pre-selected properly regardless of spacing or case variations in your stored data.

just use explode() in the controller after you’ve got the data. like $data['selected_types'] = explode(',', $data['userInfo']->home_type); then in the view, use in_array('apartment', $selected_types) to see if each checkbox should be checked.