PHP: Conditionally add array elements

$headers=array(
     $requestMethod." /rest/obj HTTP/1.1",
     "listable-meta: ".$listablemeta,
     "meta: ".$nonlistmeta,
     'accept: */*',
      );

In the above example, I would like to omit the entire line if $ listablemeta or $ nonlistmeta is empty. Suppose $ listablemeta is empty. Then the array will be:

$headers=array(
     $requestMethod." /rest/obj HTTP/1.1",
     "meta: ".$nonlistmeta,
     'accept: */*',
      );

Now I can configure conditional isempty () and set the array accordingly, but what if I want to build an array with about 20 different values, each of which sets only if the variable on each line is not empty, is there another way to set the conditional -within is an array declaration? If not, how can this problem be approached?

Thank!

+3
source share
3 answers

- , , :

, , :

$requestMethod = 'GET';
$listablemeta = ''; // This shouldn't be in the final result
$nonlistmeta = 'non-listable-meta';

/ :

$headers = array(
               0 => $requestMethod." /rest/obj HTTP/1.1",
               'listable-meta' => $listablemeta,
               'meta' => $nonlistmeta,
               'accept', '*/*'
           );

, , requestMethod, . :

function buildHeaders($headers) {
    $new = array();

    foreach($headers as $key => $value) {
        // If value is empty, skip it
        if(empty($value)) continue;
        // If the key is numerical, don't print it
        $new[] = (is_numeric($key) ? '' : $key.': ').$value;
    }

    return $new;
}

$headers = buildHeaders($headers);

$headers - :

$headers = array(
               'GET /rest/obj HTTP/1.1',
               'meta: non-listable-meta-here',
               'accept: */*'
           );
+1

, , :

$headers = array(
  $requestMethod." /rest/obj HTTP/1.1",
  "meta: ".$nonlistmeta,
  'accept: */*'
);

$items = array(
  "item1" => "",
  "item2" => "foo"
);

foreach ($items as $key => $val) {
  if ($val != "") {
    $headers[] = $val; // only 'foo' will be passed
  }
}
+2

I don't know how to do this in the declaration, but a simple helper function could do without tricks:

function array_not_empty($values){
  $array = array();
  foreach($values as $key=>$value){
    if(!empty($value)) $array[$key] = $value;
  }
  return $array;
}
+1
source

Source: https://habr.com/ru/post/1727275/


All Articles