Question

This is probably a silly question:

I am doing the following to set the headers in an array that I convert to a CSV download. The CSV part is irrelevant to this question as it works just fine.

Array Headers:

$csv_fields  = array();
$csv_fields[0]   = array();
$csv_fields[0][] = 'Category';
$csv_fields[0][] = 'Question';
$csv_fields[0][] = 'Case';
$csv_fields[0][] = 'Partner';
// ... etc

Now I want to set the heads based on check boxes that are Posted to the script. I was going to use lots of if, else statements like so:

if ($_POST['category']) {

    $csv_fields[0][] = 'Category';

elseif ($_POST['question']) {

    $csv_fields[0][] = 'Question';

}
// .... etc

But thought there might be a better way using Ternary Operator. I tried the following, but of course if the $_POST is not set, it still adds a null value to the array, so I get gaps in my headers.

$csv_fields[0][] = isset($_POST['category']) ? 'Category' : NULL;
// ... etc

I end up with something like:

[0] => 
[1] => Question
[2] => 
[3] => Partner
// ... etc

So my question is, how can I use the Ternary Operator to just skip rather than set the array value if the $_POST variable is not set?

Or is there a better way?

Thanks

Was it helpful?

Solution

I don't think a tenary operator could help you with this.. But you could shorten your code, because it's a lot of boilerplate and you could move everything to an loop.

$vars = array(
    'category' => 'Category',
    // ...
);

foreach ($vars as $name => $text) {
    if (isset($_POST[$name])) {
        $csv_fields[0][] = $text;
    }
}

OTHER TIPS

You could use ternary in combination with array_merge().

$csv_fields[0] = array_merge($csv_fields[0], 
                             isset($_POST['category']) ?
                             array('Category') : array());

It's neither pretty or efficient. Better use a loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top