简体   繁体   中英

Check for empty values in associative array

I'm having a hard time checking for empty values in my associative array. And if a value is empty/null replace it with the wording "not entered"

My $_SESSION['gift'] array:

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);
}

The above outputs:

I give my 1a to 2a.
I give my 1b to .

I would like it read:

I give my 1a to 2a.
I give my 1b to not entered .

You can replace all empty and NULL value with not entered with the help of array_walk_recursive and use you code as it is

 array_walk_recursive($arrayMain, 'not_entered');

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

You should modify your code and write it this way:

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";
    }
}

You might want to try this:

 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);
}

If you would like to make it a little cleaner you could extract the ternary operator into something like this;

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

Try:

$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.';
  }
}

Just use foreach to loop all values and check if it's 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
}

I'd write that this way:

$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";
    });
}

You can use for the below code also there is no need any extra Php functions.

$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;

This validates an associative array with empty() (see array_filter ), but may not respond to the original question.

<?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);

Other functions used here: array_flip() , array_intersect_key() , count() , extract() , var_dump() ,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM