Aims:
$rainfalls = array(3, 2, 2, 1, 3);
$total = 0;
$size = 0;
echo "<table>";
foreach ($rainfalls as $rainfall)
{
echo "<tr><td>{$rainfall}</td></tr>";
$total = $total + $rainfall;
$size = $size + 1;
}
echo "</table>";
$avg = $total / $size;
echo "<p>{$avg}</p>";
$total = $total + $rainfall;
$total += $rainfall;
-=, *=, /=, %= and
.=
$x contains after
each statement in this sequence:
$x = 5; $y = 6; $x += 5; $x /= 2; $x += $y; $x %= 10;
$size = $size + 1;
$size++;
++$size;
$x = $x - 1; $x -= 1; $x--; --$x;
echo $x = 22;
$x++ and ++$x:
| Operator | Name | Effect on $x | Value returned |
|---|---|---|---|
$x++ | Post-increment | Incremented | Original |
++$x | Pre-increment | Incremented | New |
$x--) and pre-decrement (--$x) operators$x contains after
each statement in this sequence, and give the output:
$x = 5; $x++; ++$x; echo $x++; echo ++$x; echo $x;
$rainfalls = array(3, 2, 2, 1, 3);
$total = 0;
$size = 0;
echo "<table>";
foreach ($rainfalls as $rainfall)
{
echo "<tr><td>{$rainfall}</td></tr>";
$total += $rainfall;
$size++;
}
echo "</table>";
$avg = $total / $size;
echo "<p>{$avg}</p>";
count( $a )
returns the number of elements in array $a (sizeof is an
alias for count)
array_sum( $a )
returns the sum of every element in the array
count function and not the array_sum function
explode( $delim, $str )
splits a string into an array, e.g.:
$string_of_planets = 'mercury venus earth'; $array_of_planets = explode( ' ', $string_of_planets );It's handy for getting input from the user and creating an array from it
trim( $str )
removes spaces from the beginning and end of a string, e.g.:
$string_of_planets = ' mars jupiter saturn '; $trimmed_string_of_planets = trim( $string_of_planets );
$trimmed contain:
$trimmed = trim( ' ' );
<form action="word_count.php" method="get">
<input type="text" name="sentence" />
<input type="submit" />
</form>
word_count.php,
which tells the user how many words s/he entered:
$sentence = trim( $_GET['sentence'] );
if ( $sentence != '' )
{
$array_of_words = explode( ' ', $sentence );
echo '<p>You typed ' . count( $array_of_words ) . ' words.</p>';
}
strlen( $str )
returns the length of (number of characters in) string $str, e.g.:
$how_many = strlen( 'uranus' ) + strlen( '' ) + strlen( ' ' ); echo $how_many;
<form action="non_space_count.php" method="get">
<input type="text" name="sentence" />
<input type="submit" />
</form>
non_space_count.php (next slide),
which tells the user how many characters s/he entered, excluding the spaces between words
$sentence = trim( $_GET['sentence'] );