PHP code example of oc / world-countries

1. Go to this page and download the library: Download oc/world-countries library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

oc / world-countries example snippets


use Oc\WorldCountries\WorldCountries;

$world = new WorldCountries();

$pakistan = $world->country('PK');
$regions = $world->regions('PK');
$punjab = $world->region('PK', 'PB');

$world = new WorldCountries();

// Find by ISO 3166-1 alpha-2
$pakistan = $world->country('PK');

// Find by ISO 3166-1 alpha-3
$pakistan = $world->countryByAlpha3('PAK');

// Check existence (alpha-2 or alpha-3)
$exists = $world->hasCountry('pak');

// Get all countries
$countries = $world->countries();

// Search countries (case-insensitive, partial match)
$results = $world->searchCountries('pak');

// Build dropdown options: ['PK' => 'Pakistan', ...]
$options = $world->countryOptions();

// Get all regions for a country (alpha-2 or alpha-3)
$regions = $world->regions('PK');
$regions = $world->regions('PAK');

// Find a specific region
$punjab = $world->region('PK', 'PB');

// Check region existence
$exists = $world->hasRegion('PK', 'PB');

// Search regions within a country
$results = $world->searchRegions('PK', 'pun');

// Build dropdown options: ['PB' => 'Punjab', ...]
$options = $world->regionOptions('PK');

use Oc\WorldCountries\WorldCountries;
use Oc\WorldCountries\Repositories\CountryRepository;
use Oc\WorldCountries\Repositories\RegionRepository;
use Oc\WorldCountries\Support\DataPathResolver;

$countryRepository = new CountryRepository(
    dataPathResolver: new DataPathResolver('/path/to/custom/data'),
);

$regionRepository = new RegionRepository(
    countryRepository: $countryRepository,
    dataPathResolver: new DataPathResolver('/path/to/custom/data'),
);

$world = new WorldCountries($countryRepository, $regionRepository);