1

I was hoping to see is there a better way to check those array keys, if they exist. i am using basic if statement

$rules = array( 
    'extensions' => ['png', 'gif', 'jpg', 'jpeg'],
    'mimes' => ['image/png', 'image/gif', 'image/jpeg', 
    ]);

if (in_array($mime_type, $rules['mimes']))
      {
        echo "<br>Valid Image!<br>>";
      }
else
      {
        echo "<br>Ivalid Image!<br>>";
        }   

if (in_array($file_type, $rules['extensions']))
      {
    echo "<br>Valid Extension<br>";
      }
else
      {
    echo "<br>Ivalid Extension<br>";
  }
Adnan
  • 101
  • 2
  • 10

2 Answers2

2

Your code seem good to me, but to spare some lines, you can use, array_walk_recursive(), i.e:

$result = [];
array_walk_recursive($rules, function ($item) use (&$result, $file_type, $mime_type)
{
    if (preg_match("@$mime_type|$file_type@i", $item))
    {
        $result[] =  $item;
    }
}
);
if (count($result) > 1) {
    print "both values";
   }
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • 1
    it worked, thanks allot for your time, and yes it spared me from allot of if statements – Adnan Apr 28 '17 at 00:42
1

Are you checking for keys/values? In your question title it says keys but you are searching for values in the above code. To get value, if its a simple one dimension array in_array will help. To get keys you can check using array_key_exists. If its a multidimensional array, try like this : https://stackoverflow.com/a/19421079/6863825 you can modify the logic to get both key/val in the same function. Let me know if it helps.

Community
  • 1
  • 1
NSK
  • 31
  • 5