[PHP's Basic Rules] Master Variables and Associative Arrays to Create a Profile Card!
In the last article, we created a "Quote of the Day" page that changes its message based on the day of the week using PHP. I hope you were able to experience the fun of having PHP run on the server to dynamically generate HTML.
This time, we'll learn the core of PHP programming: "how to handle data." Specifically, you'll gain two important weapons: the "variable," for storing a single piece of data, and the "associative array," for managing multiple related pieces of data together.
By the time you finish this article, you will have learned the basics of manipulating information with PHP, and in the end, you'll be able to create your own **original profile card** like the one below. It's a very practical piece of content that you can use immediately as a self-introduction widget just by changing the information to your own. Let's get started!
Are You Ready to Run PHP?
Before we get to the main topic, an important check. To run the code in this article, you need a server environment where PHP can operate. If you haven't set up a development environment on your computer yet, please refer to this article first to get set up.
[PHP for Beginners] A Complete Guide to Downloading and Installing XAMPP!
If you're all set, let's move on to the next step!
1. Variables: "Boxes" for Storing Data
In programming, a "variable" is like a "named box" for storing data such as numbers or strings of text. In PHP, variable names must always start with a dollar sign ($).
For example, to handle your site's title or your name in PHP, you would write it like this:
<?php
// Store a string in the $site_title variable
$site_title = "My Profile Page";
// Store a string in the $my_name variable
$my_name = "Jane Doe";
// Store a number in the $age variable
$age = 28;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo $site_title; ?></title>
</head>
<body>
<p>Hello, I'm <?php echo $my_name; ?>. I am <?php echo $age; ?> years old.</p>
</body>
</html>
The line $my_name = "Jane Doe"; means "put the text string 'Jane Doe' into the box named `$my_name`." Once you've put data into a variable, you can use echo to call up its contents anywhere, as many times as you like.
2. Associative Arrays: "Shelves with Name Tags" for Related Data
Profile information includes many related pieces of data, like a name, role, and hobbies. Managing each of these in separate variables (`$name`, `$role`, `$hobby`...) becomes difficult as the number of items grows.
This is where the "array" comes in. An array is a larger box that can manage multiple pieces of data together. The type that's especially common in PHP is the "associative array," which is like a "shelf with name tags" that lets you manage data not with numbers, but with a "name (key)."
How to Create and Use an Associative Array
If you want to manage profile information in an associative array, you can write it like this:
<?php
// Store profile information in an associative array called $profile
$profile = [
'name' => 'Taro Yamada',
'role' => 'Web Designer',
'hobby' => 'Cafe hopping on weekends',
'comment' => 'I strive to create simple and user-friendly designs.'
];
?>
Here, 'name' and 'role' are the "keys (name tags)," and the part to the right of the => is the "value (the contents)."
To retrieve a specific piece of data from the array, you specify it in the format array_name['key'].
<?php
$profile = [
'name' => 'Taro Yamada',
'role' => 'Web Designer',
'hobby' => 'Cafe hopping on weekends',
'comment' => 'I strive to create simple and user-friendly designs.'
];
// Specify the 'name' key to retrieve and display the value
echo $profile['name']; // Result: Taro Yamada
echo '<br>'; // For a line break
// Specify the 'comment' key to retrieve and display the value
echo $profile['comment']; // Result: I strive to create simple and user-friendly designs.
?>
As you can see, by using an associative array, you can manage highly related data like a profile as a single, very easy-to-understand unit.
The Final Product: A "Profile Card" That Works with Copy-Paste
Now, let's combine our knowledge of variables and associative arrays to complete our final goal: the "Profile Card."
【IMPORTANT】Copy all of the code below and create a file named profile.php. Then, place that file in your XAMPP's designated `htdocs` folder and access it in your browser via a URL like http://localhost/profile.php.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Profile</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background-color: #eef2f7; padding: 2rem; }
.profile-card {
background-color: white;
border-radius: 15px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
max-width: 400px;
width: 100%;
text-align: center;
padding: 2.5rem;
border-top: 5px solid #007bff;
}
.profile-img { width: 120px; height: 120px; border-radius: 50%; object-fit: cover; border: 4px solid #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.15); margin-bottom: 1rem; }
.profile-name { font-size: 1.8rem; font-weight: 600; color: #333; margin: 0; }
.profile-role { font-size: 1.1rem; font-weight: 300; color: #777; margin-top: 0.25rem; }
.profile-divider { border: 0; height: 1px; background-color: #eee; margin: 1.5rem 0; }
.profile-info p { font-size: 1rem; color: #555; line-height: 1.6; text-align: left; margin: 0.5rem 0; }
.profile-info p strong { color: #333; margin-right: 0.5em; }
</style>
</head>
<body>
<?php
// Manage all profile information in one associative array
$profile = [
'name' => 'Jane Doe',
'role' => 'Frontend Engineer',
'hobby' => 'Photography, Traveling',
'comment' => 'I aim to create intuitive and memorable UI/UX for users.',
'image_url' => 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?q=80&w=300' // Put your image URL here
];
?>
<div class="profile-card">
<img src="<?php echo $profile['image_url']; ?>" alt="Profile Picture" class="profile-img">
<h2 class="profile-name"><?php echo $profile['name']; ?></h2>
<p class="profile-role"><?php echo $profile['role']; ?></p>
<hr class="profile-divider">
<div class="profile-info">
<p><strong>Hobby:</strong><?php echo $profile['hobby']; ?></p>
<p><strong>Quote:</strong><?php echo $profile['comment']; ?></p>
</div>
</div>
</body>
</html>
Did a beautiful profile card appear in your browser? By simply changing the contents of the $profile array in the PHP section to your own information, you can easily create a self-introduction card. Feel free to swap out the image URL and have some fun with it.
Advanced Application: Automatically Generating Multiple Staff Profile Cards
What if you want to introduce multiple staff members? Copying and pasting the profile card code for each person would be a lot of work. That's where programming comes in handy.
By combining a nested structure ("an array within an array," or a multi-dimensional array) and the "looping" (foreach) we touched on in the previous article, you can automatically generate cards for all your staff members.
<?php
// Store multiple staff profiles as an array of arrays
$staff_list = [
[
'name' => 'John Smith', 'role' => 'Director', 'comment' => 'I lead our projects to success.', 'image_url' => 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?q=80&w=300'
],
[
'name' => 'Jane Doe', 'role' => 'Designer', 'comment' => 'I create designs that leave a lasting impression.', 'image_url' => 'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?q=80&w=300'
],
[
'name' => 'Peter Jones', 'role' => 'Engineer', 'comment' => 'I build stable and reliable systems.', 'image_url' => 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?q=80&w=300'
]
];
?>
<!-- The display HTML is outside the loop -->
<div class="staff-container">
<h1>Our Team</h1>
<div class="card-grid">
<?php foreach ($staff_list as $staff_member): ?>
<div class="profile-card">
<img src="<?php echo $staff_member['image_url']; ?>" class="profile-img">
<h2 class="profile-name"><?php echo $staff_member['name']; ?></h2>
<p class="profile-role"><?php echo $staff_member['role']; ?></p>
<p><?php echo $staff_member['comment']; ?></p>
</div>
<?php endforeach; ?>
</div>
</div>
The foreach loop takes each element (each staff member's profile array) from the $staff_list array one by one and generates an HTML card for it each time. No matter how many staff members you add, you only need to add their data to the PHP array, which is extremely efficient.
Summary
Great work! This time, we learned the most fundamental ways to handle data in PHP.
- Variables: Store a single piece of data (like a string or a number) in a named box that starts with
$. - Associative Arrays: Manage multiple related pieces of data as a single unit using the
['key' => 'value']format. - By combining these with HTML, you can create manageable and reusable content like profile cards, where data and design are separated.
Being able to organize and handle data in the form of "variables" and "arrays" is a major step in programming. This concept is a crucial foundation for more advanced processes you'll encounter later, such as database integration.
Next time, we'll learn about "control structures (like if statements)," which allow your programs to make decisions, like "if this is true, do that"!