PHP: Sorting an array

This entry is part 22 of 54 in the series PHP Tutorial

Array can be sorted easily using the sort function.

<?php
 
$gift = array("TV","car","aeroplane", "iPad", "iPhone", "PS4"); 

echo "Before Sorting:\n";
echo "$gift[0] $gift[1] $gift[2] $gift[3] $gift[4] $gift[5]";


sort($gift);
echo "\n\n";
echo "After sorting:\n";
echo "$gift[0] $gift[1] $gift[2] $gift[3] $gift[4] $gift[5]";


?>

Another more elegant way of printing out the array is to use a for loop:

<?php
 
$gift = array("TV","car","aeroplane", "iPad", "iPhone", "PS4"); 

echo "Before Sorting:\n";
echo "$gift[0] $gift[1] $gift[2] $gift[3] $gift[4] $gift[5]";


sort($gift);

echo "\n\n";
for ($i=0; $i <= 5; $i++)
   {
    echo "$gift[$i]\n"; 
   }
?>

PHP: Array count

This entry is part 21 of 54 in the series PHP Tutorial

To get the no of elements in an array, we can use the count function.

Here we pass the $gift array into the count function.

<?php
 
$gift = array("TV","car","aeroplane", "iPad", "iPhone", "PS4"); 

$gift_count = count($gift);
 
echo "I have $gift_count gifts.";

?>

PHP: Array

This entry is part 20 of 54 in the series PHP Tutorial

An array is an ordered list.

It can be created using the array() language construct.

<?php 

$gift = array("TV","car","aeroplane"); 

echo "I want a " . $gift[0] . ", a " . $gift[1] . ", and an " . $gift[2];											
?>

The gift array is first constructed using an array() statement.

Items in the array will be put in a list accessible by gift[0], gift[1] and gift[2].

PHP: Arithmetic operators

This entry is part 19 of 54 in the series PHP Tutorial

Arithmetic operators work just like those we learnt in school.

ExampleNameResult
-$aNegationOpposite of $a
$a + $bAdditionSum of $a and $b.
$a - $bSubtractionDifference of $a and $b.
$a * $bMultiplicationProduct of $a and $b.
$a / $bDivisionQuotient of $a and $b.
$a % $bModulusRemainder of $a divided by $b.
<?php

echo (5 % 3);           
echo '<br>';
echo (5 + 3);         
echo '<br>';
echo (5 - 3);  
echo '<br>';
echo (12 / 4);  

?>

PHP: String operators

This entry is part 17 of 54 in the series PHP Tutorial

Earlier, we have used .(dot) to join 2 strings together.

<?php

$text1 = 'Hello ';
$text2 = $text1 . 'World!'; 

echo "$text2";
echo "\n";

$text3 = 'Upwhere We ';
$text3 .= 'Belong!';  

echo "$text3";
echo "\n";

$num = 3;

echo "Result: " . ($num + 3); 

?>

In the statement $text3 .= ‘Belong!’, the .(dot) here is a unary string operator.

The statement here will add ‘Belong!’ to variable $text3 itself.