Checkeach array item has a value
I am trying to error check a form that on submitting creates an array, however no valu开发者_StackOverflow社区e in that error can be empty, how can I check this using PHP, the array looks like this,
Array
(
[campaign_title] =>
[campaign_keyword] =>
[introduction] =>
[position] => left
[campaign_headline] => Array
(
[0] =>
)
[article] => Array
(
[0] =>
)
[save_multiple] => Save
)
I know I would need to do something like below but from then I am totally lost,
foreach($post as $k=>$v) {
//do some loop to check each key as a value?
}
foreach($post as $k=>$v) {
if(is_array($v)) {
foreach($v as $k1=>$v1) {
if(empty($v1))
throw new Exception($k1.' inside '.$k.' is empty');
}
}
if(empty($v))
throw new Exception($k.' is empty');
}
Here is another solution. Works for multidimensional arrays too and will throw an Exception when it finds an empty
value:
array_walk_recursive($array, function($val, $key) {
if (empty($val)) {
throw new Exception(htmlspecialchars($key).' is empty');
}
});
Requires PHP5.3 due to the Lambda callback.
The following function will check all values in the array, regardless of depth. It will return TRUE when it finds an empty value. Otherwise it will return FALSE.
function hasEmptyValues(array $array)
{
foreach(new RecursiveIteratorIterator(
new RecursiveArrayIterator($array)) as $v) {
if(empty($v)) return TRUE;
}
return FALSE;
}
function check_array($array)
{
foreach($array as $key => $value)
{
if(is_array($value))
{
check_array($value);
}
if(!isset($value))
{
return FALSE;
}
}
return TRUE;
}
usage: check_array($_POST);
Ok, a little bit unorthodox solution
First serialize the array
$serialized_array = serialize($your_array);
It will turn out like this
a:6:{s:14:"campaign_title";s:0:"";s:16:"campaign_keyword";s:0:"";s:12:"introduction";s:0:"";s:8:"position";a:1:{i:0;s:0:"";}s:7:"article";a:1:{i:0;s:0:"";}s:13:"save_multiple";s:4:"Save";}
You can count empty values by counting "".
$number_of_empty_values = substr_count($serialized_array, '""');
Do you want, that no Value can be empty?
Then here:
<?php
function checkArrayIsEmpty( $array )
{
foreach( $array as $k => $v )
{
if( is_array( $v ) )
{
checkArrayIsEmpty( $v );
}
elseif( !is_array( $v ) && empty( trim( $v ) ) )
{
return TRUE;
}
}
return FALSE;
}
?>
use this like:
<?php
if( checkArrayIsEmpty( $post ) )
{
echo 'Error!';
}
else
{
echo '...'; // Its not empty
}
?>
精彩评论