php - Undefined variable Array Slim Application
I am getting this error that runs fine on one of my servers with php 5.4 I transfered the code to a new server with php 5.5.9 and now I am getting this error:
Details
Type: ErrorException Code: 8 Message: Undefined variable: propertylist File: /var/www/subdomains/api/index.php Line: 57 Trace
The code:
$app->get("/propertylist/", function () use ($app, $db) {
$app->response()->header("Content-Type", "application/json");
ob_start('ob_gzhandler');
$req = $app->request();
$bed = $req->get('bed');
$bath = $req->get('bath');
$city = $req->get('city');
$zip = $req->get('zip');
if($bed ==''){$bed=0;}
if($bath ==''){$bath=0;}
if($zip ==''){
$properties = $db->rets_property_listing_mrmls_resi->limit(2500,0)->where("Bedrooms >= ?", $bed)->where("City LIKE ?", "%$city%")->where("BathsTotal >= ?", $bath);
}else{
$properties = $db->rets_property_listing_mrmls_resi->limit(2500,0)->where("Bedrooms >= ?", $bed)->where("ZipCode LIKE ?", "%$zip%")->where("BathsTotal >= ?", $bath);
}
foreach ($properties as $property) {
$propertylist[] = array(
"MLSnumber" => $property["MLnumber"],
"ListPrice" => number_format($property["ListPrice"]),
"StreetNumber" => $property["StreetNumber"],
"StreetName" => $property["StreetName"],
"SqFt" => $property["SquareFootageStructure"],
"PropertyDescription" => summaryMode($property["PropertyDescription"],15),
"Bedrooms" => $property["Bedrooms"],
"BathsTotal" => $property["BathsTotal"],
"LO_Name" => $property["LO_Name"]
);
}
echo json_encode($propertylist);
});
Answer
Solution:
You need create/define variable before use:
Answer
Solution:
I think that version of PHP just changed the variables' scope, now it's more like you expect in other languages. If you define/create a variable in a block, it's not visible in the outer scope.
In your case,
$propertylist
is defined directly in theforeach
block scope, hence it isn't visible to the rest of the code, causing the error.As @Guilherme Nascimento suggested, you have to define it outside the loop.
That's said, in PHP is perfectly fine (but not recommended) to use a variable without instantiate it: