Esquire Theme by Matthew Buchanan
Social icons by Tim van Damme

26

May

PHP Arrays Ex. #1: Simple Array

Let’s brief a bit on Arrays before moving on into this question. Please read the question at http://phpexercises.com/php-simple-array-exercise.html

There are two types of Arrays in PHP:

  • Numerical Array or Index
  • Associative Array

A Numerical or Indexed array will have numbers for it’s keys. So for example, $a[0] = ‘somebody’, $a[1] = ‘else’, $a[2] = ‘elsewhere’. So in this example we have a numerical key starting from 0 all the way to the number 2. That’s 3 records on the array. In the Associative Array, the key or indexer is a string and not a number. So an example would be something like $a[‘Ravi’] = ‘programmer’, $a[‘Gehlot’] = ‘last name’.

In this exercise, we are going to build an Associate Array with the weather conditions listed out. The exercise did not specify weather to use numerical or associative. The code below is what I came up with for an associative array:

<?php
$listWeatherConditions = array(‘rain’ => ‘rain’
                                ,    ’sunshine’ => ‘sunshine’
                                ,    ’clouds’ => ‘clouds’
                                ,    ’hail’ => ‘hail’
                                ,    ’sleet’ => ‘sleet’
                                ,    ’snow’ => ‘snow’
                                ,    ’wind’ => ‘wind’
                                );
?>
<!DOCTYPE html>
<html>
<head>
      <title>My Weather Condition Array page</title>
</head>
<body>
      <h3>My Weather Condition Array Page</h3>
<?php
echo ‘We've seen all kinds of weather this month. At the beginning of the month, we had ’ .
$listWeatherConditions[‘snow’] . ’ and ’ . $listWeatherConditions[‘wind’] . ‘. Then came ’ .
$listWeatherConditions[‘sunshine’] . ’ with a few clouds and some ’ . $listWeatherConditions[‘rain’] .
’. At least we didn't get any ’ . $listWeatherConditions[‘hail’] . ’ or ’ . $listWeatherConditions[‘sleet’] . ‘.’;
?>
</body>
</html>

The code below is what I came up with for a numerical array:

<?php
$listWeatherConditions = array(‘rain’, ‘sunshine’, ‘clouds’, ‘hail’, ‘sleet’, ‘snow’, ‘wind’);
?>
<!DOCTYPE html>
<html>
<head>
      <title>My Weather Condition Array page</title>
</head>
<body>
      <h3>My Weather Condition Array Page</h3>
<?php
echo ‘We've seen all kinds of weather this month. At the beginning of the month, we had ’ .
$listWeatherConditions[5] . ’ and ’ . $listWeatherConditions[6] . ‘. Then came ’ .
$listWeatherConditions[1] . ’ with a few clouds and some ’ . $listWeatherConditions[0] .
’. At least we didn't get any ’ . $listWeatherConditions[3] . ’ or ’ . $listWeatherConditions[4] . ‘.’;
?>
</body>
</html>

Go to http://phpexercises.com/php-simple-array-exercise.html to look at the original code answer from phpexercises.com. What I like about their code is that they took the time to write code comments. Comments are part of good code standards.