Errol Paleracio
Errol Paleracio

Reputation: 634

How to pass variable only if it is set in php

I use CodeIgniter form helper. I only want to pass the $incident->street_id variable if it is set. I don't want to use if so is there any way to reduce to one line probably cause it will just be a clutter if I use if else.

echo form_dropdown(
    'street',
    $streets,
    $incident->street_id,
    'class="form-control required"'
);

Upvotes: 1

Views: 155

Answers (3)

shakeel osmani
shakeel osmani

Reputation: 736

 <?php echo form_dropdown('street', $streets, isset($incident->street_id) ?:  'NULL', 'class="form-control required"');?>

Upvotes: 0

ROAL
ROAL

Reputation: 1779

You are probably looking for the ternary operator, which is basically a shorthand for if/else.

<?php echo form_dropdown('street', $streets, isset($incident->street_id) ? $incident->street_id : '', 'class="form-control required"');?>

The syntax is as follows:

condition ? ture : false

Upvotes: 1

user4486345
user4486345

Reputation:

    <?php 
echo form_dropdown('street', $streets, isset($incident->street_id)?$incident->street_id:"else if it doesnt set", 'class="form-control required"');
?>

Upvotes: 0

Related Questions