检查关联数组中的空值

Check for empty values in associative array

我很难检查关联数组中的空值。如果一个值是 empty/null 将其替换为 "not entered"

我的$_SESSION['gift']数组:

Array
(
    [0] => Array
        (
            [giftGiveMy] => 1a
            [giftTo] => 2a
        )

    [1] => Array
        (
            [giftGiveMy] => 1b
            [giftTo] => '' //### empty ###
        )

)



 if (empty($_SESSION['gift']) && 0 !== $_SESSION['gift']) {
    $gifts = "No specific gifts identified.\n";
 } else {
    $gifts = [];
    foreach( $_SESSION['gift'] as $value) {
        $gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $value['giftTo'] .".\n";
    }
    $gifts = join($gifts);
}

以上输出:

我把我的 1a 给 2a。
我把我的 1b 给 .

我想阅读:

我把我的 1a 给 2a。
我把我的 1b 给 not entered.

你应该修改你的代码,这样写:

if (!isset($_SESSION['gift']) || empty($_SESSION['gift'])) {

     $gifts = "No specific gifts identified.\n";

} else {

    foreach( $_SESSION['gift'] as $value) {

        $gift_to = !empty($value['giftTo']) ? $value['giftTo'] : '<strong>Not entered<strong>';
        $gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $gift_to .".\n";
    }
}

您可能想试试这个:

 if (empty($_SESSION['gift']) && 0 !== $_SESSION['gift']) {
    $gifts = "No specific gifts identified.\n";
   } else {
    $gifts = [];
    foreach( $_SESSION['gift'] as $value) {
        $gifts[] = "I give my ". $value['giftGiveMy'] ." to ". (!empty($value['giftTo']) ? $value['giftTo'] : '<b>not entered</b>') .".\n";
    }
    $gifts = join($gifts);
}

如果你想让它更干净一点,你可以将三元运算符提取到这样的东西中;

$giftTo = !empty($value['giftTo']) ? $value['giftTo'] : '<b>not  entered</b>';
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $giftTo .".\n";

尝试:

$arr =  $_SESSION['gift'];
foreach($arr as $key => $array) {
  if($array['giftGiveMy'] == null || empty($array['giftGiveMy'])) {
    $arr[$key]['giftGiveMy'] = 'not entered.';
  }
  if($array['giftTo'] == null || empty($array['giftTo'])) {
    $arr[$key]['giftTo'] = 'not entered.';
  }
}

只需使用foreach循环所有值并检查它是否为empty

$emptyText = '<b>not entered</b>';

// `empty` will also be true if element does not exist 
if (empty($_SESSION['gift'])) {
    $gifts = "No specific gifts identified.\n";
} else {
    $gifts = [];

    foreach($_SESSION['gift'] as $value) {
        $myGive = !empty($value['giftGiveMy']) ? $value['giftGiveMy'] : $emptyText;
        $giftTo = !empty($value['giftTo']) ? $value['giftTo'] : $emptyText;
        $gifts[] = "I give my {$myGive} to {$giftTo}.";
    }

    $gifts = implode("\r\n", $gifts); // Or `<br/>` if outputted to HTML
}

您可以在 array_walk_recursive 的帮助下用 not entered 替换所有空值和 NULL 值,并按原样使用您的代码

 array_walk_recursive($arrayMain, 'not_entered');

    function not_entered(& $item, $key) {
    if (($item === "") || ($item ==NULL)){
        $item = "not entered";
    }
}
var_dump($arrayMain);

我会这样写:

$gifts = "No specific gifts identified.\n";

$filter = function($str) {
               return empty($str) ? 'not entered' : $str;
          };

if(!empty($_SESSION['gift'])) {
    $gifts = '';
    array_walk($_SESSION['gift'], function($given) use(&$gifts,$filter){
        $gifts .= 'I give my ' . $filter($given['giftGiveMy']) . ' to ' . $filter($given['giftTo']) . ".\n";
    });
}

您可以使用下面的代码,也不需要任何额外的 Php 函数。

$arr = array(
    0 => array(
        'giftGiveMy' => '1a',
        'giftTo' => '2a'
    ),
    1 => array(
        'giftGiveMy' => '1b',
        'giftTo' => ''
    )
);

$str = '';
if (!empty($arr)) { 
    foreach ($arr as $key => $value) {
        if ($value['giftGiveMy'] == '')
            $value['giftGiveMy'] = 'not entered';
        if ($value['giftTo'] == '')
            $value['giftTo'] = '<strong>not entered</strong>';
        //$new[$key] = $value;
        $str .= "I give my " . $value['giftGiveMy'] . " to " . $value['giftTo'] . "<br />";
    }
}else {
    $str = 'No specific gifts identified.<br />';
}

echo $str;

这验证了具有 empty() 的关联数组(参见 array_filter),但可能无法回答原始问题。

<?php

$var = array();
$var['position'] = 'executive';
$var['email'] = 'a@email.com';
$var['message'] = 'This is the message';
$var['name'] = 'John Doe';
$var['telephone'] = '123456789';
$var['notneededparam'] = 'Nothing';

$expectedParams = ['position', 'email', 'message', 'name', 'telephone'];

$params = array_intersect_key($var, array_flip($expectedParams));

// check existence of keys and that they are valid
if(count($params) != count($expectedParams) || count(array_filter($params)) != count($expectedParams)){
    echo "not valid\n";
    die();
}

extract($params);

var_dump($name);

此处使用的其他函数:array_flip(), array_intersect_key(), count(), extract(), var_dump()