开发者

How to create a string taking empty variables into consideration?

I'm trying to build a placeholder meta description for a page, in case the user hasn't included a description in the CMS.

I have started with the following code, but of course it fails if any of the other variables are empty too, such as $phone, $location['zip'] and so on.

<?php   
if (!empty($description)) {
    echo '<meta name="description" content="' .$description . '">';
}
else {
    // Should return: Apple is a business located in Palo Alto, 95014. Call 408.996.1010...
    $description = $name . ' is a ' . strtolower($category) . ' located in ' . $location['city']  . ', ';
    $description .= $location['zip'] . '. Call ' . $phone . ' for more details today.';
    echo '<meta name="description" content="' . $description . '">'开发者_C百科;        
} ?>

What's the most efficient way to build a description in this way? Currently I can only think of nested if statements which sounds messy and I'm sure there must be a clean way to do this.


add a function to check if value is set?

i.e.

function checkData($data) {
   if(!empty($data)) {
      return $data;
   } else {
     return '';
   }
}

$description = checkData($name) . ' is a ' . strtolower(checkData($category)) . ' located in ' . checkData($location['city'])  . ', ';


As the description is something that varies based on the input, put it into a function or class of it's own to encapsulate it:

/**
 * build a description based on various input variables
 * @return string
 */
function build_description($description, $name, $category, array location, $phone) {
   // build the description as you see fit.
}

$description = build_description(compact('description', 'name', 'category'));
$metaDescription = sprintf('<meta name="description" content="%s"', htmlspecialchars($description));

that done, the concrete implementation within build_description can contain a lot of complex statements, while the rest of the program can deal with it as if it is something simple.

However, this does not answer how you could code it inside that function. But as the data of the output of that function heavily depends on the input of that function, you can only deal with all aspects the arguments do impose.


The other variables defined shouldn't be string but part of an object such as... Description. In this case, it would be easier, calling a Description->isEmpty() that returns true if one of those variables are empty.

If you are stuck with this configuration, you still can make an array: $myArray=array($name, $category,...); and check in a loop or maybe the return of in_array('',$myArray)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜