0

my multidimensional array is

Array (    
            [0] => Array ( 
                       [questionID] => 47
                       [surveyID] => 51
                       [userID] => 31 
                       [question_Title] => Choose Any One? 
                       [question_Type] => Dropdown 
                       [response] => 1.Android 2.Windows 3.Blackberry 
                       [required] => 0 
                       [add_time] => 0
            )
            [1] => Array ( 
                       [questionID] => 48 
                       [surveyID] => 51 
                       [userID] => 31 
                       [question_Title] => Is it? 
                       [question_Type] => Bigbox 
                       [response] => Yes No 
                       [required] => 1 
                       [add_time] => 0 
            )    

        )

then using foreach loop i submit each value and insert it in MySQL db but if [required] => 1 exist in array i don't want to submit any values

so,how to check weather whole array conatins [required] => 1

3 Answers3

0

Seems a simple enough foreach loop will do the trick:

foreach($mainArray as $miniArray)
{
    if($miniArray['required']==1)
    {
        // Do insert stuff here.
    }
}

Or if you want to check whether it exists ANYWHERE in the array before you enter it, a simple boolean should do the trick:

$hasRequired=false;
foreach($mainArray as $miniArray)
{
    if($miniArray['required']==1)
    {
        $hasRequired=true;
    }
}

if($hasRequired)
{
    // Do Insert Stuff here.
}
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
0

You can use array_filter:

$test_array = array(
    array(
        "required"=>0,
        "other_field"=>"value"
    ),
    array(
        "required"=>0,
        "other_field"=>"value"
    ),
    array(
        "required"=>0,
        "other_field"=>"value"
    ),
);

function checkIfRequired($var)
{
    return (is_array($var) && $var['required'] == 1);
}

if(sizeof(array_filter($test_array, "checkIfRequired"))){
    print 'required field exists';
}
else{
    print 'required field does not exist';
}
Emil Condrea
  • 9,705
  • 7
  • 33
  • 52
0

You can use is_array or in_array function to check the the value of an array. But is_array function is faster and accurate than in_array. And here is an example from the php manual . This function will check through whole array .

    function myInArray($array, $value, $key){
//loop through the array
foreach ($array as $val) {
  //if $val is an array cal myInArray again with $val as array input
  if(is_array($val)){
    if(myInArray($val,$value,$key))
      return true;
  }
  //else check if the given key has $value as value
  else{
    if($array[$key]==$value)
      return true;
  }
}
return false;

}

monirz
  • 534
  • 5
  • 14