Search code examples
phparrayscodeigniterexplode

Explode function is not working properly


I am getting output from the database which is working. Below array displaying the proper output.

 $get_elements = array(
        'student_elements' => $row->student_elements, 
        'address_elements' => $row->address_elements,  
        'marketing_elements' => $row->marketing_elements, 
        'office_use_elements' => $row->office_use_elements, 
 );

Getting output

Array
(
    [student_elements] => firstname,lastname,mobileno,age,gender
    [address_elements] => building,sector,city
    [marketing_elements] => 
    [office_use_elements] => counsellername,mobile,email
)

Now I pass the array value in explode function

$result_elements=explode(',',$get_elements);

Getting error

Severity: Warning
Message:  explode() expects parameter 2 to be string, array given

I want to pass the $result_elements in foreach

$results = [];
foreach ($result_elements as $value) {
    echo $sql_elements_get="SELECT fields_name, fields_type FROM `tbl_form_builder_fields` WHERE fields_name='".$value."'";
    $fetch_query = $this->db->query($sql_elements_get);
    foreach ($fetch_query->result() as $r){
        $results[] = $r;
    }
}
return $results;// I

I want to run the query each an every time to get the output of each value which coming from explode function.

Would you help me out in this?


Solution

  • It looks like you're trying to get a list of all unique elements in all of the strings. As others have mentioned, you cannot explode an array. One way you could loop through this would be to implode the array together, then explode it.

    <?php
    $get_elements = array (
        'student_elements'     => 'firstname,lastname,mobileno,age,gender',
        'address_elements'     => 'building,sector,city',
        'marketing_elements'     => NULL,
        'office_use_elements'     => 'counsellername,mobile,email'
    );
    
    // Combine all strings
    $get_elements = implode(',',$get_elements);
    
    // DEBUGGING ONLY
    echo $get_elements;
    
    // Split the elements
    $get_elements = explode(',', $get_elements);
    
    // DEBUGGING ONLY
    echo '<pre>'.var_export($get_elements, TRUE).'</pre>';
    
    // YOUR CODE
    $results = [];
    foreach ($get_elements as $value) {
        // Ensure it's not empty
        if($value != ''){
            echo $sql_elements_get="SELECT fields_name, fields_type FROM `tbl_form_builder_fields` WHERE fields_name='".$value."'";
            $fetch_query = $this->db->query($sql_elements_get);
            foreach ($fetch_query->result() as $r){
                $results[] = $r;
            }
        }
    }
    return $results;
    
    ?>
    

    A Codepad link for the output of your code (removing the database calls).