// 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
";
}
}
// Using single quotes to print double quotes
echo '
Total number of blanks '.$blankCount.'
';
// 4. Alternative array iteration; cannot access array index easily
echo '';
foreach ($dataArray as $item) echo '- '.$item.'
';
echo '
';
// 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 '';
foreach ($histogramData as $key=>$value) {
echo '- '.$key.": ".$value.'
';
}
echo '
';
*/
// 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 '';
echo '';
echo ''.$key.'';
echo '
';
}
?>