Using Arrays in PHP
PHP is similar to a lot of other languages I’ve seen in terms of creating and using arrays. One interesting feature I saw today was the ability to nest arrays within arrays, rather than creating a 2D (or 3D or 4D…) array. I’m not sure where this functionality might be advantageous, but I can certainly imagine that it might be.
Additionally, there are a number of array functions that allow for analysis of arrays. If an array contains only numeric values, for example, it’s easy to run statistics on the array. There are also a number of functions for taking strings and creating arrays, or taking arrays and creating long strings.
The code below demonstrates a number of array functions. Again, simply copy this code into a text editor and save it as a .php file, then point your browser to it.
<html>
<head>
<title>
Array Functions
</title>
</head>
<body>
<?php $array1 = array(14,38,55,116,2,4); ?>
Count: <?php echo count($array1); ?> <br />
Max Value: <?php echo max($array1); ?> <br />
Min Value: <?php echo min($array1); ?> <br />
<br />
Sort: <?php sort($array1); print_r($array1); ?> <br />
Reverse Sort: <?php rsort($array1); print_r($array1); ?> <br />
<br />
Implode: <?php echo $string1 = implode(” * “, $array1); ?> <br />
Explode: <?php print_r(explode(” * “,$string1)); ?> <br />
<br />
In array: <?php echo in_array(15, $array1); // returns T/F ?> <br />
</body>
</html>
-
loganabbott liked this
-
30daysatatime posted this