I am wondering if it is possible to search an array, with another array's values. So if there is 2 arrays, Array a and Array b - array a will see if its values as any results in array b.
define('L001', 'Wrong Password');
define('L002', 'Form not filled in');
define('L003', 'Account is not active');
$errors = array ('L001', 'L002', 'L003');
$args = explode('/', rtrim($_SERVER['QUERY_STRING'], '/'));
if (isset($args) && in_array($errors, $args)) {
if (in_array($errors[0], $args)) {
$error = L001;
} elseif (in_array($errors[1], $args)) {
$error = L002;
} elseif (in_array($errors[2], $args)) {
$error = L003;
}
} else {
//no errors
}
Is something like this possible?
The code above doesn't work in my head. Additionally, in_array() will only work on whole arrays, not an element of one. More sensible would be:
$errors = array('L001' => 'Wrong Password',
'L002' => 'Form not filled in',
'L003' => 'Account is not active');
if(isset($args) && in_array($args, $errors)) {
echo $errors[$args]; // will output the text
} else {
// no errors
}
You could alternatively assign $errors[$args] to a variable for later use if you don't want to output it right there and then with $error = $errors[$args];
I would recommend array_intersect()
or array_intersect_key()
depending on how you set up the static $errors
array.
Code:
$errors = array ('L001'=>'Wrong Password', 'L002'=>'Form not filled in', 'L003'=>'Account is not active');
$QS='L002/L003/L005/'; // some test querystring data
$args = explode('/', rtrim($QS,'/'));
$found_errors=array_intersect_key($errors,array_flip($args)); // no need to check isset() on $args
var_export($found_errors);
echo "
";
// or if you just want the first one:
echo current($found_errors);
Output:
array (
'L002' => 'Form not filled in',
'L003' => 'Account is not active',
)
Form not filled in