The Red Penguin

Associative Arrays


Saturday 14 November 2020

A simple guide to associative arrays
// This file creates an array and adds "scores" to it

// Create empty associative array

$categories = [];

// Append some elements to it

$categories += ["music" => 1];
$categories += ["walks" => 1];
$categories += ["westham" => 1];

// "music" is in the array, so this code adds 1 to the value of "music"

$find = "music";
$categories[$find] = $categories[$find] + 1;

// "cpp" is not in the array, so the same code adds it to the array with a value of 1

$find = "cpp";
$categories[$find] = $categories[$find] + 1;

// Make a value change

$cat = "walks";
$categories[$cat] = $categories[$cat] + 2;

// Print the array

print_r($categories);

// Create second array

$teams = [];

// Create new array of words to count

$words = array("chips", "music", "python", "walks", "cpp", "python", "beer", "music", "music", "python", "walks", "walks", "cpp", "cpp", "python", "walks", "music", "music", "cpp", "python", "music", "walks");

// Loop through counting incidence of each one

for ($i = 0; $i < count($words); $i++) {
$teams[$words[$i]] = $teams[$words[$i]] + 1;
}

print_r($teams);

// sort array in descending order

arsort($teams);

print_r($teams);

// input result a different way now

echo "Total posts: " . array_sum($teams) . " - ";
foreach ($teams as $key => $value) {
$result .= $key . " " . $value . ", ";
}

// remove last comma from $result

echo substr(trim($result), 0, -1);


More posts in php