Q:

json encode and php array

I am trying to get the following output that will produce the following json
[{"description":"name","errorcode":777},{"description":"Department","errorcode":"yyy"}]

PHP
if(empty($name)){        
    $errordesc[] = array('description' => 'name','errorcode' =>  777);           
}
else if(empty($email)){
    $errordesc[] = array('description' => 'Department','errorcode' =>  "yyy");
}

when I do 
 echo json_encode($errordesc);

it gives output as 
[{"description":"name","errorcode":-2}]

The problem is in the php array.Should I use array_push?
Please advice.Thanks in advance.

A:

The is a syntax error in your code 
else if(empty($email){<-----here

else if(empty($email)){<-----must be like this 

Seeing your code actually i think the array contains only one item ,that is why you get that out put array push is not required just correct your logic.
 $errordesc[] = array('description' => 'name1','errorcode' =>  1); 
 $errordesc[] = array('description' => 'name2','errorcode' =>  2); 

echo json_encode($errordesc);

you will get json string with two items 
[{"description":"name1","errorcode":1},{"description":"name2","errorcode":2}]

A:

Your code currently has the following structure:
if (condition) {
    # code...
} 
elseif (condition) {
    # code...
}

The code inside this block will get executed only if the first if condition evaluates to FALSE. The JSON output you're getting suggests that only one of the conditional blocks is being considered.
If you want to do both the checks, try using the following structure:
if (condition) {
    # code...
} 
if (condition) {
    # code...
}

With your code, it should look like:
if(empty($name)){        
    $errordesc[] = array('description' => 'name','errorcode' =>  777);           
}
if(empty($email)) {
    $errordesc[] = array('description' => 'Department','errorcode' =>  "yyy");
}

Demo!

