I am using the CodeIgniter framework to create my web services. I have an optional parameter that I want to set its value according to:-
Method 1
$foo = $this->post('foo');
if(isset($foo) && $foo == 0) {
$var2 = 'a';
} else {
$var2 = 'b';
}
Method 2
$foo = $this->post('foo');
if(isset($foo)) {
if ($foo == 0)
$var2 = 'a';
else
$var2 = 'b';
} else {
$var2 = 'b';
}
Both methods are returning $var2 = 'a'
when I do not send in foo
.
try below, both are same.
$foo = $this->input->post("username");
$var2 = (int)$foo === 0 ? 'a' : 'b';
OR
$foo = $this->input->post("username");
if((int)$foo === 0)
$var2 = 'a';
else
$var2 = 'b';
NOTE: you are using isset()
to check an empty string. That is why it returns true
always.
Hope this helps :)
you not using correct method to getting post value try
$foo = $this->input->post('foo');
if(empty($foo)) {
$var2 = 'a';
} else {
$var2 = 'b';
}
$this->input->post()
The function returns FALSE (boolean) if the item you are attempting to retrieve does not exist.
so instead try something like this
if(isset($_POST['foo']) && $_POST['foo'] == 0) {
$var2 = 'a';
} else {
$var2 = 'b';
}
or
$foo = $this->input->post('foo');
if($foo && $foo == 0){
$var2 = 'a';
} else {
$var2 = 'b';
user this code
$foo = $this->input->post('foo');
if(isset($foo) && $foo == '0') {
$var2 = 'a';
} else {
$var2 = 'b';
}
echo " variable =". $var2;
Output:
variable = a // if you enter 0 in foo field
variable = b // if you didn't enter 0
You have to use single quotes around 0 (Zero) in if condition
if(isset($foo) && $foo == '0')
$foo = $this->input->post('foo');
var_dump($foo );
check the value of $foo then write candition, may be $foo return false value
Fixed it using === '0'
.
$foo = $this->post('foo');
if($foo === '0') {
$var2 = 'a';
} else {
$var2 = 'b';
}