开发者

Check if all array elements are set

开发者 https://www.devze.com 2023-03-17 23:22 出处:网络
I have the following ar开发者_StackOverflow社区ray: $my_array = array ( \'city\'=> $this->input->post(\'city\'),

I have the following ar开发者_StackOverflow社区ray:

$my_array = array ( 
                 'city'     => $this->input->post('city'),
                 'country'  => $this->input->post('country'),
                 'state'    => $this->input->post('state'),
                 'miles'    => $this->input->post('miles')
                 );

Which short php function or method can I use to check if all array items are set? Right now I'm using the following code

$my_array = array_filter($my_array);

if (!empty($my_array['city']) && !empty($my_array[['miles']) && !empty($my_array[['state']) && !empty($my_array['country']))
{
     //do something
}

note: I'm using the array_filter() function to remove all entries from a query that equal FALSE.


It seems like you can just count the number of elements left after filtering:

if(count($my_array) == 4){
    // all 4 still set
}


In general, you can do this:

$required = array_flip(array('city', 'country', 'state', 'miles'));
if (array_diff_key($required, $my_array)) {
    // not all keys are set
}

In this specific case though, counting the resulting array should indeed be enough.


In that case? I'd just test count(array_values($my_array)) == 4.


Try this:

function testArray($array) { 
 for($x = 0,$len = count($array); $x < $len; $x++) {
     if(empty($array[$x])) {
          return false; 
      }
  }
         return true; 
}

short function:

count(array_map('empty', $array)) == count($array)
0

精彩评论

暂无评论...
验证码 换一张
取 消