I want to compare two arrays, one is set by default and another by user input.
When I have set a boolean value only in the default so I want to make sure the user won’t use string or number. for instance, ‘truex’ or ‘1’ is not acceptable.
Below is my sample of code,
$default = array(
"randomise" => false,
"id" => null
);
$config = array(
"randomise" => truex
);
function process_array($default,$config)
{
# Loop the array.
foreach($default as $key => $value)
{
if ((filter_var($default[$key], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === NULL) && (filter_var($config[$key], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === NULL))
{
return 'true or false only';
}
}
# Return the result.
return $array;
}
print_r(process_array($default,$config));
but this code returns ‘true or false only’ even though the user provides the correct data type. how can I fix this?
Alright first up you need to check that
$configcontains the key in$default. [Asside: If$configis user supplied… they could never user-supply an object like that, perhaps you meant$config=array("randomize"=>"truex");.. unless by user supplied you mean some other developer as the user (not a web user)).Second of all
$config['id']will always fail the test as you’ve written it (because it’s not a boolean).So, I’m trying to guess at what you’re doing here but I think this is what you want…