Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does in_array() not work on $_POST?

I'm trying to check that user's submitted data, from $_POST, has at least the same elements that my passed array has. I'm doing it because I will use those elements later by calling $_POST['element'] and I don't like errors about that element doesn't exist (isn't set). :)

I don't want to use something like isset($_POST['x'], $_POST['y'], $_POST['z']) because each time I need to rewrite $_POST and it seems unreadable as well.

I tried to use in_array(array('x', 'y', 'z'), $_POST), but it doesn't work (it returns false when it should return true). Any ideas how to make that work? :) I'm sure that I have empty strings as $_POST['x'], $_POST['y'] and $_POST['z']. I even tried to change values of hose three $_POST elements to something other than empty string - still... doesn'y work as expected. :(

Thanks in an advice! :)

Edit:

Just found out that in_array() checks values, not keys. Then, I tried to do like this...

in_array(array('title', 'slug', 'content'), array_keys($_POST))

Still, it returns false. How does it comes so? ;/

Edit #2:

Okay, here are results of debugging...

Incoming $_POST:

array(3) {
    ["title"]=>
    string(0) ""
    ["slug"]=>
    string(0) ""
    ["content"]=>
    string(0) ""
}

Result of array_keys($_POST):

array(3) {
    [0]=>
    string(5) "title"
    [1]=>
    string(4) "slug"
    [2]=>
    string(7) "content"
}

Result of in_array(array('title', 'slug', 'content'), array_keys($_POST)):

bool(false)

The question... why is it false? I did all correct, as much as I know.

Edit #3:

At the end, I created my own method called Arr::keys_exists($keys, $array).

like image 521
daGrevis Avatar asked Oct 08 '11 16:10

daGrevis


2 Answers

in_array() checks to see if a value exists in an array, not a key. If you want to check to see if a key exists, then you'd want something like...

in_array('x', array_keys($_POST));

or the simpler...

array_key_exists('x', $_POST);

If you want to check for many keys at once:

$required_keys = array('x'=>1, 'y'=>1, 'z'=>1);
$missing_keys = array_diff_key($required_keys, $_POST);
$missing_keys_count = count($missing_keys);
like image 172
Amber Avatar answered Sep 18 '22 19:09

Amber


Because in_array checks if the needle is in the array exactly. See example #3 of the manual-page. array_key_exists cannot work with a key as first argument because array's aren't valid with arrays as keys.

You want something like all_in_array(array $needles, array $haystack); or array_all_keys_exists(array $keys, array $search); which returns whether all elements are in the array. You can probably implement something like this yourself, or ask for more help here.

like image 32
ontrack Avatar answered Sep 22 '22 19:09

ontrack