Search code examples
phparraysassociative-arrayarray-key

explode an array and add array keys


I have a string that looks like this,

IT, MEDIA, ADVERTISING

I am then doing the following code.

$criteria = explode(",", $string);

This obviously creates the following when print_r is run over the $criteria.

array([0] => IT, [1] => MEDIA, [2] => 'ADVERTISING')

I using $criteria to match for keywords in a database in codeigniter application, I am wanting to using something like,

$this->db->like($criteria);

for this to work though I need the $criteria array to look like this,

array([sector] => IT, [sector] => MEDIA, [sector] => 'ADVERTISING')

How can I do this?


Solution

  • If you're trying to make OR WHERE clauses with an array like this:

    $criteria = array(
        0 => 'IT',
        1 => 'MEDIA',
        2 => 'ADVERTISING',
    )
    

    You can loop through it and use like() and or_like() methods:

    foreach ($criteria as $index => $value) {
        if ($index == 0)
            $this->db->like('sector', $value);
        else
            $this->db->or_like('sector', $value);
    }
    
    // Produces WHERE sector LIKE '%IT%' OR sector LIKE '%MEDIA%' OR sector LIKE '%ADVERTISING%';