0

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'
)
3
  • you want to return value only or a new array as you shown? Commented Jun 16, 2015 at 12:53
  • Using array_search function Commented Jun 16, 2015 at 12:54
  • Please do some try, show us your code, then we may help, instead of just giving you the solution :) Commented Jun 16, 2015 at 12:54

4 Answers 4

1

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']
Sign up to request clarification or add additional context in comments.

Comments

1

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;}});

Comments

1

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.

Comments

0

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'];}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.