3v4l.org

run code in 300+ PHP versions simultaneously
<?php $json = <<<EOT { "results" : [ { "address_components" : [ { "long_name" : "Winnetka", "short_name" : "Winnetka", "types" : [ "locality", "political" ] }, { "long_name" : "New Trier", "short_name" : "New Trier", "types" : [ "administrative_area_level_3", "political" ] }, { "long_name" : "Cook County", "short_name" : "Cook County", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "Illinois", "short_name" : "IL", "types" : [ "administrative_area_level_1", "political"] }, { "long_name" : "Switzerland", "short_name" : "CH", "types" : [ "country", "political" ] }, { "long_name" : "United States", "short_name" : "US", "types" : [ "country", "political" ] } ], "formatted_address" : "Winnetka, IL, USA", "geometry" : { "bounds" : { "northeast" : { "lat" : 42.1282269, "lng" : -87.7108162 }, "southwest" : { "lat" : 42.0886089, "lng" : -87.7708629 } }, "location" : { "lat" : 42.10808340000001, "lng" : -87.735895 }, "location_type" : "APPROXIMATE", "viewport" : { "northeast" : { "lat" : 42.1282269, "lng" : -87.7108162 }, "southwest" : { "lat" : 42.0886089, "lng" : -87.7708629 } } }, "place_id" : "ChIJW8Va5TnED4gRY91Ng47qy3Q", "types" : [ "locality", "political" ] }, { "address_components" : [ { "long_name" : "Winnetka", "short_name" : "Winnetka", "types" : [ "locality", "political" ] }, { "long_name" : "New Trier", "short_name" : "New Trier", "types" : [ "administrative_area_level_3", "political" ] }, { "long_name" : "Cook County", "short_name" : "Cook County", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "Illinois", "short_name" : "IL", "types" : [ "administrative_area_level_1", "political"] }, { "long_name" : "United States - 2", "short_name" : "US", "types" : [ "country", "political" ] } ], "formatted_address" : "Winnetka, IL, USA", "geometry" : { "bounds" : { "northeast" : { "lat" : 42.1282269, "lng" : -87.7108162 }, "southwest" : { "lat" : 42.0886089, "lng" : -87.7708629 } }, "location" : { "lat" : 42.10808340000001, "lng" : -87.735895 }, "location_type" : "APPROXIMATE", "viewport" : { "northeast" : { "lat" : 42.1282269, "lng" : -87.7108162 }, "southwest" : { "lat" : 42.0886089, "lng" : -87.7708629 } } }, "place_id" : "ChIJW8Va5TnED4gRY91Ng47qy3Q", "types" : [ "locality", "political" ] } ], "status" : "OK" } EOT; $data = json_decode($json); $counties = []; if(!empty($data->results)){ $counties = array_filter($data->results[0]->address_components, function ($address) { return in_array('administrative_area_level_2', $address->types); }); } if(!empty($counties)){ echo reset($counties)->long_name; }else{ echo 'No county found'; }
Output for 5.6.38, 7.2.0 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
Cook County

preferences:
143.39 ms | 407 KiB | 5 Q