i have an Array
, when i print it i get the following output;
Array[{"city":"London","school":"st patrick"}]
Now i want to read the item saved in variable city
and check if its London
in the IF
condition below;
if ($cityArray['city'] == 'London') {
echo 'City present';
}
My if condition above, is incorrect, i am not getting the expected output. I guess the way i am accessing the city
item is incorrect.
A couple of things. Your array looks to be JSON format. You'll want to decode using json_decode (after fixing the format of the array):
$jsonArray = Array('{"city":"London","school":"st patrick"}'); // User the correct PHP array format: Array() while the inside elements should be quoted if they're strings.
$cityArray = json_decode($jsonArray[0]);
Use the correct variable reference format:
if ($cityArray->city == 'London') { // $cityArray is an object, so you'll need to use the -> operator to get its "city" property.
echo 'City present';
}
The way you're trying to access the value of the associative array (by inputting the name to return the value) is correct, but just need to fix a couple of formatting issues, is all.
Edit: Added index number of array to get the JSON.
This is a JSON string, you need to decode it first:
$data = json_decode($json);
Then you can access the elements like so:
for ($i = 0; $i < count($data); $i++) {
$element = $data[$i];
echo $element->city;
}