Stan Stan - 4 months ago 11
PHP Question

Remove all array elements except what I want?

I have controller that takes post parameters from HTML form, it will then send them to model that will insert the array into Cassandra database.

It is SQLInjection proof, because it's NoSQL, however what I'm afraid is that user can just simulate 100k post parameters or just add some that I don't need and it will be inserted into database. How can I make sure that only the values I need will stay in my array.


$post = ['parent_id', 'type', 'title', 'body', 'tags']; // Good
$post = ['parent_id', 'type', 'title', 'body', 'tags', 'one', 'two', 'three'] // Bad

How do I make sure that my array will unset all the elements that are not in good example?

Jon Jon

You are looking for array_intersect:

$good = ['parent_id', 'type', 'title', 'body', 'tags'];
$post = ['parent_id', 'type', 'title', 'body', 'tags', 'one', 'two', 'three'];

print_r(array_intersect($good, $post));

See it in action.

Of course this specific example does not make much sense because it works on array values, but there is also array_intersect_key that does the same based on keys.