Utilizing PHP Associative Arrays for Effective Data Management

Introduction to the Lesson

Welcome back! This tutorial focuses on PHP Associative Arrays — versatile data structures ideal for managing key-value pairs. Through two illustrative problems, you'll enhance your ability to create and utilize associative arrays, gaining crucial skills to tackle real-world challenges efficiently.

Problem 1: Count Word Frequencies in a Text

Imagine we have a blog. We want to analyze the posts to determine which topics are most discussed. A practical solution involves writing a function to count the frequency of each word in a blog post while ignoring case and punctuation.

This function is essential in text analysis tools used in search engine optimization. It can highlight popular topics and even suggest post tags, increasing visibility in search results.

Problem 1: Naive Approach

One might think to manually tally word occurrences — a tedious and inefficient approach involving extra loops and slow performance. Our time is too valuable for such inefficiency.

Problem 1: Efficient Approach

Instead, PHP's associative arrays provide a handy way to map each unique word to its frequency count effortlessly. With this in mind, we can track how often each word appears with concise and faster code!

Let's start by creating a function and cleaning up our input: removing punctuation and converting it to lowercase for consistency.

PHP
function countWordFrequencies($text) {
    $normalizedText = strtolower(preg_replace('/[^\w\s]/', '', $text));

We split the cleaned text into various words, ready for counting.

PHP
    $words = preg_split('/\s+/', $normalizedText);
    $frequencyArray = [];

We use the associative array to keep track of the count for each word, incrementing it for each occurrence.

PHP
    foreach ($words as $word) {
        if (isset($frequencyArray[$word])) {
            $frequencyArray[$word]++;
        } else {
            $frequencyArray[$word] = 1;
        }
    }

    return $frequencyArray;
}

Here is the full code!

PHP
<?php
// Function to count word frequencies in a given text
function countWordFrequencies($text) {
    // Normalize the text by removing punctuation and converting to lowercase
    $normalizedText = strtolower(preg_replace('/[^\w\s]/', '', $text));
    // Split the text into words
    $words = preg_split('/\s+/', $normalizedText);
    $frequencyArray = [];

    // Count the frequency of each word
    foreach ($words as $word) {
        if (isset($frequencyArray[$word])) {
            $frequencyArray[$word]++;
        } else {
            $frequencyArray[$word] = 1;
        }
    }

    // Return the associative array containing word frequencies
    return $frequencyArray;
}

// Example text for counting word frequencies
$text = "Hello world! Hello, PHP world. PHP is great; is it not?";
print_r(countWordFrequencies($text));
?>

Here, we have an associative array where keys are words, and values are counts — a direct mirror of our text analysis goals.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal