Abdall Abdall - 1 year ago 144
JSON Question

PHP Cannot Access Empty Element only when input is 0

I am brand new to PHP and I thought my code was working but there seems to be a slight bug.

This is my code:


$string = file_get_contents("jsontest.txt");
$result = json_decode($string);

if(isset($_POST['value']) && !empty($_POST['value']) &&
isset($_POST['whatElement']) && !empty($_POST['whatElement']) &&
isset($_POST['category']) && !empty($_POST['category']) &&
isset($_POST['model']) && !empty($_POST['model'])) {

$value = $_POST['value'];
$whatElement = $_POST['whatElement'];
$category = $_POST['category'];
$model = $_POST['model'];

$result->$category->$model->$whatElement = $value;
echo $result->$category->$model->$whatElement;

$myfile = fopen("jsontest.txt", "w") or die("Unable to open file!");
$txt = json_encode($result);
fwrite($myfile, $txt);

I was using this as a response to an HTML input tag. If it is relevant this is the javascript code that I use to call my PHP script

function handleEnter(value, type, exactModel)
var bothParts = exactModel.split("_");
category = bothParts[0];
model = bothParts[1];

url: "morework.php",
data: {value: value, whatElement: type, category: category, model: model},
type: 'post',
success: function(ret){


This passes the proper data to the PHP script but when the "value" variable is set as 0 I get the following: "Fatal error: Cannot access empty property in..."

I have tried to change the code as follows:

Instead of:
$result->$category->$model->$whatElement = $value;

I put:
$result->category->model->whatElement = $value;

This seems to handle the error but does not change the json file at all. Whereas if I had the original it does not work for 0 but does change the json file for all other numbers.

I have used var_dump on $_POST and in all cases this seems to hold the correct values. However if I do send in a 0 if I echo this line:
echo "$value $whatElement $category $model";
it shows up as empty whereas it is populated when non-zero

Example of the var_dump for a 0 value test:

array(4) {
string(1) "0"
string(8) "Borrowed"
string(9) "Category"
string(8) "Model"

An explanation as to what is happening/advice on how to remedy this is greatly appreciated.

Omi Omi
Answer Source

The following things are considered to be empty (php manual):

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
array() (an empty array)
$var; (a variable declared, but without a value)

So your conition will fail when you have 0 value. You can remove isset($_POST['value']) && !empty($_POST['value']) this from condition. Write this before if condition

if your php version is 7.0 or greater use

 $value =  $_POST['value'] ?? 0;

if php version less than 7.0 use

 $value = isset($_POST['value']) && !empty($_POST['value']) ? $_POST['value']:0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download