简体   繁体   中英

Using is_numeric in shorthand coding in checking the variable if it is a string or numeric

Having a hard time trying to figure out how I can use ternary operations in trying to determine if the value of a variable inside is a number/integer or a string. If it is a number it will display the $score with text or words inside. If it is a text or string it will only show the value. Having a

$score = 42

$variables['page']['sidebar_first']['block_scored']['#markup'] = '<div id="entry-score"><h3><span>' . (is_numeric($score)) . '</span></h3></div>';

尝试做三元:

(is_numeric($score) ? $score : null)

At the current time, you are displaying either true, if $score is a number or false, if it is not and are not using the ternary operator.

The ternary operator is quite simple to use:

$result = (is_numeric($score)) ? 'number' : 'not a number';

Now $result will contain either the word 'number' if it is one or 'not a number' if it is a string or just something other then a number.

I don't fully understand your question, so please, update what exactly you are trying to accomplish.

<?php
function do_output($score)
{
    $format = ['%s', 'Your score is: %d'];
    printf($format[is_numeric($score)], $score);
}

do_output(42);
do_output('Some text that is not a number.');

Output:

Your score is: 42Some text that is not a number.

String assignment:

$output = sprintf(['<p>%s</p>', 'Your score is: <b>%d</b>'][is_numeric($score)], $score);

As you can see no ternary is required here. is_numeric is used to determine the index of the array containing output formats for s/printf.

Or with a ternary:

$output = is_numeric($score)
    ? 'Your score is: <b>' . $score . '</b>'
    : '<p>' . $score . '</p>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM