0

USE CASE :

$a = [1, 2, [3, 4, 5], [6, [7, 8], 8, 10]];
isNumberPresentInArray($a, 10) // returns true;
isNumberPresentInArray($a, 2) // returns true;
isNumberPresentInArray($a, 14) // returns false;

I would like to check if there element exist in array.The following is my version of code. but its not working perfectly for inner arrays. Please help me.

$a = [1, 2, [3, 4, 5], [6, [7, 8], 8, 10]];

function isNumberPresentInArray($a, $b) {
    foreach($a as $v)
    {
        if (is_array($v)) {
            return isNumberPresentInArray($v, $b);
        } else {
            if ($v == $b) {
                return true;
            }
        }
    }
}

echo isNumberPresentInArray($a, 1);
0

2 Answers 2

1

Your error is here :

return isNumberPresentInArray($v, $b);

You should return the result of the function only if the result is true, because, if you don't do that, you will stop the loop and don't check values after this point. You also missed the return false and get NULL instead of false if $b was not found.

function isNumberPresentInArray($a, $b) 
{
    foreach($a as $v)
    {
        if (is_array($v)) {
            if (isNumberPresentInArray($v, $b)) {
                return true;
            }
        } 
        elseif ($v == $b) {
            return true;
        }
    }
    return false;
}

Usage

$a = [1, 2, [3, 4, 5], [6, [7, 8], 8, 10]];
var_dump(isNumberPresentInArray($a, 10)); // bool(true);
var_dump(isNumberPresentInArray($a, 2)); // bool(true);
var_dump(isNumberPresentInArray($a, 14)); // bool(false);
var_dump(isNumberPresentInArray($a, 1)); // bool(true);

See also a live demo (3v4l.org).

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

Comments

1

You could use an iterator:

$arr = [ 1, 2, [ 3, 4, 5 ], [ 6, [ 7, 8 ], 9, 10 ] ];

function isNumberPresentInArray(array $arr, int $number): bool {
  $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr), RecursiveIteratorIterator::LEAVES_ONLY);
  foreach ($it as $value) {
    if ($value === $number) {
      return true;
    }
  }
  return false;
}

echo '10: ' . ( isNumberPresentInArray($arr, 10) ? 'yes' : 'no' ) . "\n";
echo ' 2: ' . ( isNumberPresentInArray($arr, 2) ? 'yes' : 'no' ) . "\n";
echo '14: ' . ( isNumberPresentInArray($arr, 14) ? 'yes' : 'no' ) . "\n";

This will print:

10: yes
 2: yes
14: no

Comments

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.