clestcruz
clestcruz

Reputation: 1111

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>';

Upvotes: 0

Views: 548

Answers (3)

Progrock
Progrock

Reputation: 7485

<?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>';

Upvotes: -1

Manuel Mannhardt
Manuel Mannhardt

Reputation: 2201

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.

Upvotes: 2

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

Try doing a ternary:

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

Upvotes: 3

Related Questions