City Zip - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of City Zip.php

  1. <?php
  2. $usstatearray = array(
  3.         'FL'=>'Florida',
  4.         'PA'=>'Pennsylvania',
  5.         'MA'=>'Massachusetts');
  6.        
  7. function getStateAbbr ($stateArray, $stateName)
  8. {
  9.     echo "Running getStateAbbr\n";
  10.     foreach ( $stateArray as $stAbbr => $stLong )
  11.     {
  12.         if ( $stateName == $stLong )
  13.         {
  14.             $stateName = $stAbbr;
  15.         }
  16.     } 
  17.     return $stateName;
  18. }
  19.        
  20.         $cityzip = '19609, Pennsylvania';
  21.         $match = array();
  22.         preg_match("/(?P<zip>\d{5})(?P<state>.*)$/",$cityzip,$match);
  23.         if($match['zip']){
  24.             $clientZipcode = $match['zip'];
  25.             $clientState = trim($match['state']);
  26.             if ( strlen($clientState) > 2 )
  27.             {
  28.                 $clientState = getStateAbbr($usstatearray,$clientState);
  29.             }
  30.             if ( empty($clientState) )
  31.             {
  32.                 $clientState = "Found in zipcodes database with zip: $clientZipcode";
  33.             }
  34.             $location = $cntyStArray[0]['County'];
  35.             $location = $location.' County';
  36.         }else{
  37.             preg_match("/(?P<city>(.+?)),(?P<state>.*)$/",$cityzip,$match);
  38.             $clientState = trim($match['state']);
  39.             echo strlen($clientState). "\n";
  40.             if ( strlen($clientState) > 2 )
  41.             {
  42.                 $clientState = getStateAbbr($usstatearray,$clientState);
  43.             }
  44.             if($match['city']){
  45.                 $location = $match['city'];
  46.             }else{
  47.                 $location = $cityzip;
  48.             }
  49.         }
  50.         echo "Client State: {$clientState}\n";
  51.         echo "Client Zip: {$clientZipcode}\n";
File Description
  • City Zip
  • PHP Code
  • 18 Oct-2019
  • 1.56 Kb
You can Share it: