0

I've been trying to figure out how to fetch all rows into an array and check if some input exists as an entry in that array.

$name = $_POST["name"];
$myarray = array();
$getnames = "SELECT NAME FROM PEOPLE";
$names = oci_parse($conn,$names);
oci_execute($names);
while (($row = oci_fetch_row($names)) != false) {
    $myarray[] = oci_fetch_row($names);
}

if(!in_array($name, $myarray)) {
      echo "That name doesn't exist.";
  }

In my table there are:

NAME
Fred
Bob
Hamlet

In the case that I used "Bob" as input, I used var_dump($myarray) just to see what was contained in that array:

array(2) { [0]=> array(1) { [0]=> string(3) "Bob" } [1]=> bool(false) }

With my output being:

That name doesn't exist.

The output is what I didn't expect it to be (as I expected "Bob" to be in the array),so I'm guessing that my method of fetching rows into an array isn't adequate.

What can I do in order for the rows to be fetched into an array?

2
  • SELECT NAME but your column is NAMES ? Commented Sep 13, 2014 at 16:47
  • My bad, it was a typo. Commented Sep 13, 2014 at 16:49

1 Answer 1

2

It's not working because Bob doesn't exist as a value in $myarray, but it's in $myarray[0][0], ie. as a value in the first item of $myarray.

You need a function that recurses into the result arrays:

function recursive_in_array($needle, $haystack) {
    if (!is_array($haystack)) return false;
    $match = false;
    foreach ($haystack as $item) {
        if (is_array($item)) $match = recursive_in_array($needle, $item);
        if ($match || in_array($needle, $haystack)) return true;
    }
    return false;
}

I only tested this quickly, but it should do the trick.

Sign up to request clarification or add additional context in comments.

2 Comments

How would I be able to use this function? Like if (recursive_in_array($name, $myarray)==true) { #do something }
Exactly, or just if (recursive_in_array($name, $myarray)) {. Both do the same thing.

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.