How to Get Gender Value by the Customer id Magento 2?

You can retrieve the customer Gender value in Magento 2 by email or customer id. Customer Gender is visible in the frontend only if the storefront allows it to display in front otherwise it will be set from the Customer Admin panel with the customer edit section.

If you have set customer gender for the customer data and want to fetch the selected value of the gender you can do it using the customer Metadata interface.

instantiate the interface Magento\Customer\Api\CustomerRepositoryInterface and Customer Repository to retrieve the selected value by model class,

<?php
namespace Jesadiya\Gender\Model;

use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Framework\Exception\NoSuchEntityException;

class CustomerGender
{
    /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepository;

    /**
     * @var CustomerMetadataInterface
     */
    protected $customerMetadata;

    public function __construct(
        CustomerRepositoryInterface $customerRepository,
        CustomerMetadataInterface $customerMetadata
    ) {
        $this->customerRepository = $customerRepository;
        $this->customerMetadata = $customerMetadata;
    }

    /**
     * Gender Value
     *
     * @param $customerId
     * @return string|null
     */
    public function getGender($customerId)
    {
        $gender = null;
        try {
            $customer = $this->customerRepository->getById($customerId);
            $genderId = $customer->getGender();
            $gender = $this->getGenderAttribute('gender')->getOptions()[$genderId]->getLabel();
        } catch (NoSuchEntityException $exception) {
            throw new LocalizedException(
                __($exception->getMessage())
            );
        }

        return $gender;
    }

    /**
     * Retrieve customer attribute instance
     *
     * @param string $attributeCode
     * @return AttributeMetadataInterface|null
     * @throws LocalizedException
     */
    protected function getGenderAttribute($attributeCode)
    {
        try {
            return $this->customerMetadata->getAttributeMetadata($attributeCode);
        } catch (NoSuchEntityException $e) {
            return null;
        }
    }
}

Call from the template or any PHP class,
$customerId = “1”;
echo $countryName = $this->getGender($customerId);

Output:
Male