Interview question
How do you check if a value exists in an array? (in_array, array_search, array_key_exists) array में वैल्यू है या नहीं कैसे चेक करें? (in_array, array_search, array_key_exists)
Answer
| Function | Checks | Returns |
|---|---|---|
| in_array($needle, $arr) | Is this value present anywhere in the array? | true / false |
| array_search($needle, $arr) | Where is this value in the array? | The key if found, false if not |
| array_key_exists($key, $arr) | Does this specific key exist? | true / false |
$fruits = ['a' => 'Apple', 'b' => 'Banana'];
in_array('Banana', $fruits); // true
array_search('Banana', $fruits); // 'b'
array_key_exists('a', $fruits); // true
isset($fruits['c']); // false, also fails if value is nullInterview tip: Explain the difference between array_key_exists() and isset() for arrays: isset() returns false if the key exists but its value is null, while array_key_exists() correctly returns true in that case.
| Function | चेक करता है | रिटर्न |
|---|---|---|
| in_array($needle, $arr) | क्या यह वैल्यू array में कहीं है? | true / false |
| array_search($needle, $arr) | यह वैल्यू array में कहाँ है? | मिले तो key, वरना false |
| array_key_exists($key, $arr) | क्या यह specific key है? | true / false |
$fruits = ['a' => 'Apple', 'b' => 'Banana'];
in_array('Banana', $fruits); // true
array_search('Banana', $fruits); // 'b'
array_key_exists('a', $fruits); // true
isset($fruits['c']); // false, वैल्यू null हो तो भी failइंटरव्यू टिप: array_key_exists() और isset() का अंतर समझाएं: key मौजूद हो पर उसकी वैल्यू null हो तो isset() false रिटर्न करता है, जबकि array_key_exists() सही तरीके से true रिटर्न करता है।
Was this answer clear?