ctf0
ctf0

Reputation: 7577

loop over items in an array and spread them in one line in php

i know its kinda stupid but what am after is,

// an array of some unknown items from the database
$array = ['item1','item2','item3'];

// i think it should be done with For loop but not sure how, so anyhow
// the loop should repeat (name contains '$item' and) for each item of the $array and put them in a query like below
foreach ($array as $item) {
    $query = [
        'q' => "name contains '$item1' and name contains '$item2' and name contains '$etc...'"
    ];
}

currently what am doing is making the query one by one which is causing overhead and with big array it takes too long, so i thought of combining the whole thing in one query which should reduce the time drastically.

Upvotes: 0

Views: 942

Answers (3)

BizzyBob
BizzyBob

Reputation: 14750

no foreach needed:

$query['q'] = "name contains " . implode(" and name contains ", $array);

but you will want to ensure the array has something in it.. :-)

Upvotes: 0

splash58
splash58

Reputation: 26153

// an array of some unknown items from the database
$array = ['item1','item2','item3'];
$q = array();
foreach ($array as $item) {
    $q[]  = "name contains '$item'";
}

$query['q'] = implode(' and ', $q);

Upvotes: 2

Bobot
Bobot

Reputation: 1118

Somethig like this should do the trick :

$array = ['item1','item2','item3'];

// init $query as array
$query = [];
// init $query 'q' index as empty string
$query['q'] = '';

// then loop the array of items, and concat what you need    
foreach ($array as $item)
{
    $query['q'] .= " name contains '$item' and";
}

// remove whitespaces from start and end of the string
$query['q'] = trim($query['q']);
// remove the ' and' from the end of the string (0 = start of string, -4 = 4 before the end of the string)
$query['q'] = substr($query['q'], 0, -4);

This will return : name contains 'item1' and name contains 'item2' and name contains 'item3'

Becare, it's a simple exemple, you should test for exemple with empty($array) that the array contains at least one item, of the substr will return false (or null, im not sure about this)

Upvotes: 1

Related Questions