How to check if multiple array keys exists?

0 votes

I have a variety of arrays that will either contain

story & message

or just

story

How would I check to see if an array contains both story and message? array_key_exists() only looks for that single key in the array.

Is there a way to do this?

Oct 27 in PHP by kartik
• 35,300 points
24 views

1 answer to this question.

0 votes

Hello @kartik,

If you only have 2 keys to check , it's probably easy enough to just call array_key_exists() twice to check if the keys exists.

if (array_key_exists("story", $arr) && array_key_exists("message", $arr)) {
    // Both keys exist.
}

However this obviously doesn't scale up well to many keys. In that situation a custom function would help.

function array_keys_exists(array $keys, array $arr) {
   return !array_diff_key(array_flip($keys), $arr);
}
answered Oct 27 by Niroj
• 76,540 points

Related Questions In PHP

0 votes
1 answer

How to check if php session is already started or not?

Hello kartik, Use session_id(), it returns an empty string ...READ MORE

answered Apr 1 in PHP by Niroj
• 76,540 points
763 views
0 votes
1 answer

How to drop a table if it exists?

Hello @kartik, No. That will drop the table only ...READ MORE

answered Jul 21 in PHP by anonymous
• 76,540 points
43 views
0 votes
1 answer

How to check if a string is JSON or not?

Hello @kartik, Use JSON.parse function isJson(str) { ...READ MORE

answered Aug 19 in PHP by Niroj
• 76,540 points
83 views
0 votes
1 answer

How to check whether property exists in object or class in php?

Hello @kartik, Using  property_exists( mixed $class , string $property ...READ MORE

answered Oct 1 in PHP by Niroj
• 76,540 points
101 views
+1 vote
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18 in Laravel by Niroj
• 76,540 points
3,435 views
0 votes
1 answer

What is redirection in Laravel?

Named route is used to give specific ...READ MORE

answered Mar 18 in Laravel by Niroj
• 76,540 points
411 views
0 votes
1 answer

How to install Laravel via composer?

Hello, This is simple you just need to ...READ MORE

answered Mar 23 in Laravel by Niroj
• 76,540 points
281 views
+1 vote
1 answer

What are named routes in Laravel and How can specify route names for controller actions?

Hey @kartik, Named routing is another amazing feature of ...READ MORE

answered Mar 23 in Laravel by Niroj
• 76,540 points
4,140 views
0 votes
1 answer

How to check if a file exists from a url using php?

Hello, You have to use CURL function does_url_exists($url) { ...READ MORE

answered Nov 3 in PHP by Niroj
• 76,540 points
63 views
0 votes
1 answer

How can one check to see if a remote file exists using PHP?

Hello @kartik, You can instruct curl to use ...READ MORE

answered Nov 10 in PHP by Niroj
• 76,540 points
26 views