PHP: Filter an array with a GET parameter

123 views Asked by At

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'
)
4

There are 4 answers

0
Mat On BEST ANSWER

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']
0
n-dru On

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'];}));
0
Narendrasingh Sisodia On

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;}});
0
Sougata Bose On

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.