Get Store code by Store id programmatically magento 2.

You can get Store code by Store id programmatically using Magento 2.

Many times, you have Store id available but you have to fetch Store code based on id, You need to use StoreManagerInterface interface.

You can fetch current Store code by below code snippet,

<?php declare(strict_types=1);

namespace Rbj\MyStore\Model;

use Psr\Log\LoggerInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Exception\LocalizedException;

/**
 * Class Config
 */
class Config
{
    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * Constructor
     *
     * @param StoreManagerInterface $storeManager
     * @param LoggerInterface $logger
     */
    public function __construct(
        StoreManagerInterface $storeManager,
        LoggerInterface $logger
    ) {
        $this->storeManager = $storeManager;
        $this->logger = $logger;
    }

    /**
     * Get Store code by id
     *
     * @param int $id
     *
     * @return string|null
     */
    public function getStoreCodeById(int $id): ?string
    {
        try {
            $storeData = $this->storeManager->getStore($id);
            $storeCode = (string)$storeData->getCode();
        } catch (LocalizedException $localizedException) {
            $storeCode = null;
            $this->logger->error($localizedException->getMessage());
        }
        return $storeCode;
    }
}

Call function,
echo $this->getStoreCodeById(1);

Output:
Returns Store code value based on Id. (for 1, its native value is default)