PHP: Conditionally add array members
$headers=array(
$requestMethod." /rest/obj HTTP/1.1",
"listable-meta: ".$listablemeta,
"meta: ".$nonlistmeta,
'accept: */*',
);
In the above example, I'd like to omit the whole line if $listablemeta or $nonlistmeta is blank. Assume $listablemeta is blank. Then the array would be:
开发者_如何学运维$headers=array(
$requestMethod." /rest/obj HTTP/1.1",
"meta: ".$nonlistmeta,
'accept: */*',
);
Now I can setup a conditional isempty() and set the array accordingly, but what if I want to construct an array with say 20 different values each only setting if the variable on each line is not empty, is there another way to set a conditional -within- an array declaration? If not, what is another way to approach this problem?
Thanks!
Loop through your options array, and if the value isn't empty, add it to your headers array:
$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
}
}
You can't do any conditionals inside the array clause that would help you with this, but this should suit your needs:
If the headers you want to pass to the array are as follows:
$requestMethod = 'GET';
$listablemeta = ''; // This shouldn't be in the final result
$nonlistmeta = 'non-listable-meta';
Build a key/value array of these variables:
$headers = array(
0 => $requestMethod." /rest/obj HTTP/1.1",
'listable-meta' => $listablemeta,
'meta' => $nonlistmeta,
'accept', '*/*'
);
Note that if the value doesn't have a key as in requestMethod
, just put a numeric value there. Then loop them through and build the final array:
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
should now contain something like this:
$headers = array(
'GET /rest/obj HTTP/1.1',
'meta: non-listable-meta-here',
'accept: */*'
);
I don't know about doing it in the declaration, but a simple helper function would propably do the trick:
function array_not_empty($values){
$array = array();
foreach($values as $key=>$value){
if(!empty($value)) $array[$key] = $value;
}
return $array;
}
精彩评论