Ivan
Ivan

Reputation: 2481

PHP: Filter an array with a GET parameter

get stuck: given an array like:

$customers = array(
    'C00005' => 'My customer',
    'C02325' => 'Another customer',
    'C01945' => 'Another one',
    'C00586' => 'ACME inc.'
)

and given a querystring like ?customerID=C01945 ($_GET['customerID'] = 'C01945' ), how can I filter the array so that it returns:

$customers = array(
    'C01945' => 'Another one'
)

Upvotes: 0

Views: 117

Answers (4)

n-dru
n-dru

Reputation: 9430

For PHP>=5.6:

$customers = array_filter($customers,function($k){return $k==$_GET['customerID'];}, ARRAY_FILTER_USE_KEY);

http://sandbox.onlinephpfunctions.com/code/e88bdc46a9cd9749369daef1874b42ad21a958fc

For earlier version you can help yourself with array_flip:

$customers = array_flip(array_filter(array_flip($customers),function($v){return $v==$_GET['customerID'];}));

Upvotes: 0

Mat
Mat

Reputation: 2154

You can just use array_instersect_key:

$myKey = $_GET['customerID']; // You should validate this string
$result = array_intersect_key($customers, array($mykey => true));
// $result is [$myKey => 'another customer']

Upvotes: 1

Sougata Bose
Sougata Bose

Reputation: 31749

Simply do -

$res = !empty($customers[$_GET['customerID']]) ? array($_GET['customerID'] => $customers[$_GET['customerID']]) : false;

You can use false or something like that to identify empty value.

Upvotes: 1

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

Try Using foreach

$customers = array(
    'C00005' => 'My customer',
    'C02325' => 'Another customer',
    'C01945' => 'Another one',
    'C00586' => 'ACME inc.'
);
$_GET['customerID'] = 'C01945';
$result = array();
foreach($customers as $key => $value){
    if($_GET['customerID'] == $key){
        $result[$key] = $value;
    }
}
print_r($result);

Using array_walk

$customerID = 'C01945';
$result = array();

array_walk($customers,function($v,$k) use (&$result,$customerID){if($customerID == $k){$result[$k] = $v;}});

Upvotes: 1

Related Questions