开发者

PHP - How to initialize an array and exclude some elements depending on a condition

开发者 https://www.devze.com 2023-03-27 16:08 出处:网络
I would like to initialize an array: $arr = array( \"date_edited\"=> time(), \"date_added\"=> ($action == \"add\" ? time() : NULL)

I would like to initialize an array:

$arr = array(
  "date_edited"  => time(),
  "date_added"   => ($action == "add" ? time() : NULL)
  ...
);

I use this array to update a database table.

Note the 2nd key, date_added. What I would like "date_added" not to be included in the array if $action is not "a开发者_JAVA百科dd". So in this case ($action != "add"), isset($arr['date_added']) should be false.

Is it possible right at the array's initialization? (I tried with NULL, but didn't work)


You can keep using your method and just filter it on declaration:

Example:

$action = "remove";
$arr = array_filter(array(
  "date_edited"     => time(),
  "date_added"      => ($action == "add"     ? time() : NULL),
  "date_removed"    => ($action == "remove"  ? time() : NULL),
  "date_approved"   => ($action == "approve" ? time() : NULL)
));

var_dump($arr); 

Will output:

array(2) { ["date_edited"]=> int(1313072949) ["date_removed"]=> int(1313072949) }


if you don't want to update the value of a field in a db, don't pass that field.

$arr = array(
  "date_edited"  => time(),
  "date_added"   => time(),
  ...
);

$tmp = $arr; // copy $arr into $tmp in case you don't want to mess with the original

if($action == "add")
{
  unset($tmp['date_added']);
}

// do your sql operation using $tmp


$arr = array(
  "date_edited"  => time(), //...
);

if($action == "add") {
 arr["date_added"] = time();
}

//EDIT

If you want to do it on initialization, you can keep your code but then have to check for is_null($arr['date_added']) instead of isset(...).

0

精彩评论

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

关注公众号