DJ Mike's Tutorials: PHP

Using Arrays pt.2


< ^ >

Sorting an array with asort()

With PHP, you can sort an array several ways. For this example, I will use asort() to sort the members of $country_code. The example on the previous page outputted a table organized by the country code. If you wanted to organize it by country name instead, you could just switch $code and $country

<?
foreach ( $country_code as $code=>$country  )
  { 
    echo 
"<tr>";
    echo 
"<td align="center">$country</td>";
    echo 
"<td>$code</td>";
    echo 
"</tr>";
  }
?>


but in the resulting table, the country names would not be alphabetical. asort() will take an array and sort it alphabetical by member, keeping the original index. As in the example above, include the file with the array but before using foreach to output the table, use asort() to sort it.

<? include("country_codes.php"); ?>
<html>
<body>
<center>
<table border="5" cellpadding="5">
<tr>
<th>Country</th>
<th>Code</th>
</tr>
<?
asort
($country_code);
foreach ( 
$country_code as $code=>$country  )

echo 
"<tr>";
echo 
"<td>$country</td>";
echo 
"<td align=\"center\">$code</td>";
echo 
"</tr>";

?>
</table>
</center>

</body>
</html>


Resulting table.

Search an array by its index.

You can search through an array by its index to find a value associated with the index like a file cabinet. To search $country_code we first need a form:

<form>
<input cols="2" maxlength="2" type="text" name="in" value="" />
<input type="submit" />
<input type="text" name="country" value="" />
</form>

Put a block of PHP at the top of your page to grab any input from the form and assign it to a variable and include the array you want to search. Use an if statement to check if the variable is set.

<?
include("country_codes.php");
$in $_REQUEST[in];
if ( isset(
$in) )
   {
   
/* search block */
   
}
?>

The user may have entered the country in capital letters so the first thing to do is use strtolower() to change the input to lower case. Next, assign an error message to $country. If a match is found, the error message will be overwritten by the country name; if not, the error message is displayed

<?
$in 
strtolower($in);
$country "No match"
?>

And now, the search begins! Using foreach(), we enter the array $country_code and assign two variables to hold the index/value pairs as foreach() loops through $country_code. For the code block to be executed for each member, enter an if statement that tests if the input is the same as the index and if it is, assign that country name to $country.

<?
foreach ( $country_code as $key=>$val  )
   {
     if ( 
$in == $key )
        { 
$country $val; }
   }
?>

Show example | Show code


< ^ >



Created by DJ Mike from Santa Barbara

DJ Mike


Dance Away Santa Barbara's Home Page
<a href="http://www.statcounter.com/" target="_blank"> <img src="http://c5.statcounter.com/counter.php?sc_project=1321035&java=0&security=da2193dc" alt="counter free hit invisible" border="0" /></a>