<?

// 1. How to get data from file
$dataString = file_get_contents("items.txt");
//var_dump($dataString);


// 2. How to convert CSV data to array
$dataArray = explode(',', $dataString);
//var_dump($dataArray);



// 3. Traditional array iteration
$blankCount = 0;
for ($i = 0; $i < sizeof($dataArray); $i++) {
	if ($dataArray[$i] == "") {
		$blankCount++;
		// Using double quotes to resolve variable names
		echo "Blank found at index $i <br>";
	}
}

// Using single quotes to print double quotes
echo '<p style="color: purple">Total number of blanks '.$blankCount.'</p>';



// 4. Alternative array iteration; cannot access array index easily
echo '<ol>';
foreach ($dataArray as $item) echo '<li>'.$item.'</li>';
echo '</ol>';


// 5. Pop last value from array
array_pop($dataArray);

// 6. Definte a new array
$histogramData = array();


// 7. Creating indices for an associative array
foreach ($dataArray as $item) {
	if (array_key_exists ($item, $histogramData)) {
		$histogramData[$item]++;
	}
	else {
		$histogramData[$item] = 1;
	}
}



// 8. Why PHP is awesoe
foreach ($dataArray as $item) {
	$histogramData[$item]++;
}


// 9. Sort the histogram data
arsort($histogramData);

/* 10. Print the histogram data
echo '<ol>';
foreach ($histogramData as $key=>$value) {
	echo '<li>'.$key.": ".$value.'</li>';
}
echo '</ol>';
*/

// 11. Print the data in a more interesting way
foreach ($histogramData as $key=>$value) {
	$width = $value*5;
	$style = 'background-color: pink; display: inline-block; height: 16px; width: '.$width.'px';
	echo '<div>';
	echo '<span style="'.$style.'"></span>';
	echo '<span>'.$key.'</span>';
	echo '</div>';
}


?>