Adrian Jelonek
Adrian Jelonek

Reputation: 27

Weird PHP "basic true / false declaration" results in two situations

I am confused with basic true / false declaration results in PHP code in two different situations. Lets assume that strlen($item["description"]) = 50. I want to add "..." if the description is longer than 20 characters.

Case 1:

$art = strlen($item["description"]) > 20 ? $item["description"] : substr($item["description"], 0, 20) . "...";
echo $art;

Case 2:

$cut = strlen($item["description"]) < 20 ? $item["description"] : substr($item["description"], 0, 20) . "...";
$art = $cut;
echo $art;

My question is: Why I have to change the "<" operator in Case 1 to ">", if I want to add "..." for bigger than 20 char desc.? In Case 2 everything works fine (the first statement is true and the second false).

Thanks for help!

Upvotes: 0

Views: 103

Answers (2)

Progrock
Progrock

Reputation: 7485

Your code reads (1), if the string is greater than 20 characters, echo the string else echo the truncated string, with the elipsis.

Whereas the logic should read something like, if the string length is greater than 20 characters echo the truncated version else echo as is.

<?php

function truncate($str) {
    return strlen($str) > 20
        ? substr($str, 0, 20) . "..."
        : $str;
}

foreach(
    [
        'Who are you?',
        'Sometimes it\'s harder to look than to leap.'
    ]
    as
        $text
)
        echo truncate($text) , "\n";

Output:

Who are you?
Sometimes it's harde...

Your second case reads fine, if the string is less than 20 chars, assign the string as is, else truncate it with the elipsis.

The ternary operator is useful shorthand for an if, else statement.

Upvotes: 0

Chopi
Chopi

Reputation: 1143

This works like this

$var = condition ? true returns : false returns

So in your case1 you have the following code

$art = strlen($item["description"]) > 20 ? $item["description"] : substr($item["description"], 0, 20) . "...";
echo $art;

You are saying in this code that if it's bigger than 20 return your text else return the substring + "..."

Instead of changing the "<" or ">" change the returns like this

$art = strlen($item["description"]) > 20 ?  substr($item["description"], 0, 20) . "..." : $item["description"] ;
echo $art;

In the second case

$cut = strlen($item["description"]) < 20 ? $item["description"] : substr($item["description"], 0, 20) . "...";

It's like

if(strlen($item["description"]) < 20)
{
    return $item["description"];
}
else
{
   return  substr($item["description"], 0, 20) . "...";
}

Upvotes: 1

Related Questions