Code Lover
Code Lover

Reputation: 8348

PHP: If Else condition assign to variable and call into string

This may be simple and silly question but first I am learning php so your help would be appreciated.

I am trying to get variable with assigned conditional statement.

$gender = $curauth->gender; // getting from wordpress user profile.

if($gender === 'Male') {
    echo 'his';
} else {
    echo 'her';
}

So what I want to do is it will check if user is Male than in some description it will use his and if female it will use her. Something like below

echo 'jatin soni doesn't have set this option yet. His option will be deactivated soon.';

So here His will be set with above conditional code.

Upvotes: 3

Views: 5853

Answers (4)

hakre
hakre

Reputation: 197767

You can echo it straight out:

echo 'jatin soni doesn\'t have set this option yet. ', 
     ($gender === 'Male' ? 'His' : 'Her'), 
     ' option will be deactivated soon.';

If you need that more than once or for readability reasons, you should assign it to a variable:

# Default Female:
$gender = empty($curauth->gender) ? 'Female' : $curauth->gender;

$hisHer = $gender === 'Male' ? 'His' : 'Her';
echo 'jatin soni doesn\'t have set this option yet. ', 
     $hisHer, 
     ' option will be deactivated soon.';

Next step could be variable substitution in double-quoted stringsDocs or the use of the printfDocs function for formatted output.

Upvotes: 5

uınbɐɥs
uınbɐɥs

Reputation: 7341

If you want a variable, you can do it in one line:

$gender = $curauth->gender; // getting from wordpress user profile.
$their = $gender == 'Male' ? $gender = 'His' : $gender = 'Her';
echo "$username doesn't have set this option yet. $their option will be deactivated soon.";

Upvotes: 1

Susam Pal
Susam Pal

Reputation: 34204

How about this?

<?php
$pronoun = $curauth->gender == 'Male' ? 'his' : 'her';
echo "Jatin Soni doesn't have set this option yet. " .
     ucfirst($pronoun) . " option will be deactivated.\n"
?>

Upvotes: 4

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28889

The most common way of doing things like this is to assign the dynamic part to a variable, and then use the variable in your output:

$gender = $curauth->gender; // getting from wordpress user profile.

if ($gender === 'Male') {
    $hisHer = 'His';
} else {
    $hisHer = 'Her';
}

echo "jatin soni doesn't have set this option yet. $hisHer option will be deactivated soon.";

Upvotes: 3

Related Questions