'display a particular string if a string variable is empty in php
I have a php class as shown below:
<?php
class helloWorld
{
public $ab;
public $cd;
public $ef;
public $gh;
public $ij;
public $kl;
public function __construct($ab = 0,
$cd = 0,
$ef = 0,
$gh = 0,
$ij = '',
$kl = '')
{
$this->ab = $ab;
$this->cd = $cd;
$this->ef = $ef;
$this->gh = $gh;
$this->ij = $ij;
$this->kl = $kl;
}
}
Problem Statement: What I want to achieve is if $kl is empty then assign ZZ to $kl.
This is what I have tried. Let me know if it looks good or if there are any changes I need to make.
<?php
class helloWorld
{
public $ab;
public $cd;
public $ef;
public $gh;
public $ij;
public $kl;
public function __construct($ab = 0,
$cd = 0,
$ef = 0,
$gh = 0,
$ij = '',
$kl = '')
{
$this->ab = $ab;
$this->cd = $cd;
$this->ef = $ef;
$this->gh = $gh;
$this->ij = $ij;
if ('' == $kl || is_null($kl)) {
$kl = 'ZZ';
}
$this->kl = $kl;
}
}
?>
Solution 1:[1]
your code is correct but it shout be short
<?php
class helloWorld
{
public $ab;
public $cd;
public $ef;
public $gh;
public $ij;
public $kl;
public function __construct($ab = 0,
$cd = 0,
$ef = 0,
$gh = 0,
$ij = '',
$kl = '')
{
$this->ab = $ab;
$this->cd = $cd;
$this->ef = $ef;
$this->gh = $gh;
$this->ij = $ij;
$this->kl = empty($kl) ? 'ZZ' : $kl;
}
}
?>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
