Friday, March 22, 2019

echo - PHP Error when echoing string

There are dozens of ways of doing this, so here's one more: printf(). It's an old school method of recomposing strings (separating parts out) that might improve readability.


# a descriptive variable name can improve readability
$posted_value = "";
if( isset( $_POST['geb_tag'] ) ) $posted_value = $_POST['geb_tag'];
for( $i = 0; $i <= 31; $i++ ) {
printf(
"",
$i,
($posted_value == $i) ? ' selected' : '',
$i
);
}

Idea is that string parts marked with %s will be replaced by appropriate parameters. Nothing wrong with concatenating strings, but it can get messy. printf() has a sprintf() variant that returns everything as a string, in case you wanted to display it later.


Lastly, there are many programmers who dislike the (statement ? '' : '') but when used appropriately, it can help. It basically means if the statement part is true, use this. If it's false, use the other part.

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...