Create customer programmatically in Magento 2.

Creating customers programmatically in Magento 2 is so simple. Just pass the required parameter to the customer array as below and create a PHP block or helper file and call createCustomer() function,

In the template file,

$customerInfo =[
    'customer' =>[
        'firstname'    => 'Rakesh1',
        'email'        => '', //customer email id
        'lastname'     => 'Jesadiya',
        'password' => 'admin123',
        'prefix' => 'Mr',
        'suffix' => ''


In the Block file, Pass customer-required data from the above $customerInfo array,


namespace Rbj\CreateCustomer\Block;

class Customer extends \Magento\Framework\View\Element\Template
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        array $data = []
    ) {
        $this->storeManager = $storeManager;
        $this->customerFactory = $customerFactory;
        parent::__construct($context, $data);

     /** Create customer
      *  Pass customer data as array
    public function createCustomer($data) {

        $store = $this->storeManager->getStore();
        $storeId = $store->getStoreId();
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $customer = $this->customerFactory->create();
        $customer->loadByEmail($data['customer']['email']);// load customer by email address
            //For guest customer create new cusotmer

Run Command,

php bin/magento indexer:reindex
php bin/magento cache:flush

Go to Admin panel, Login your admin panel with username and password, Click on Customers Tab -> All Customer

Your new customer will be generated successfully.