Horje Website
How to Create Default Profile Image Dynamically from First and Last Name in PHP

Get first letters from first and last name using PHP:
First, we need to split the full name into first name and last name and generate short characters from the user’s name.

  • Retrieve the first letters of first and last name.
  • Concat two letters to make short characters of the full name.
  1. <?php
  2. // Full name of the user
  3. $user_full_name = 'Demo User';
  4. $full_name_arr = explode(" ", $user_full_name);
  5. $full_name_arr_end = end($full_name_arr);
  6. $firstWord = !empty($full_name_arr[0])?$full_name_arr[0]:'';
  7. $lastWord = !empty($full_name_arr_end[0])?$full_name_arr_end[0]:'';
  8. $charF = !empty(mb_substr($firstWord, 0, 1))?mb_substr($firstWord, 0, 1):'';
  9. $charL = !empty(mb_substr($lastWord, 0, 1))?mb_substr($lastWord, 0, 1):'';
  10. $shortChar = $charF.$charL;
  11. ?>

Create an HTML element with the first letters of first and last name:
Print short characters of the default image in HTML.

  1. <div class="profile-image"> <?php echo trim($shortChar); ?> </div>

Define CSS to display default profile image:
Apply CSS to the selector of the HTML element (profile-image) to make it look like an image.

  1. .profile-image { width: 120px; height: 120px; border-radius: 50%; background: #512DA8; font-size: 35px; color: #fff; text-align: center; line-height: 120px; margin: 20px 0; }
November 23, 2022
Full Tutorials

This article was posted in Full Tutorials. Bookmark the permalink. Follow comments with the RSS feed for this post.Post a Comment or leave a trackback: Trackback URL.

Leave a Reply

Your email address will not be published. Required fields are marked *


Horje © 2011 - 2023