Magento 2 – How to get magento country array and their state using country code

Magento 2 – How to get magento country array and their state using country code- by Divyanshu Rohatgi

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $countrySourceModel = $objectManager->get('Magento\Directory\Model\Config\Source\Country'); 
 $countryModel = $objectManager->get('Magento\Directory\Model\CountryFactory');
 $countries = $countrySourceModel->toOptionArray();
 foreach ( $countries as $countryKey => $country ) {
 
 if ( $country['value'] != '' ) { 
 $stateData = $countryModel->create()->setId($country['value'])->getLoadedRegionCollection()->toOptionArray();
 
 if ( count($stateData) > 0 ) { 
 $countries[$countryKey]['states'] = $stateData;
 }
 
 }
 }

var_dump($countries);