2009. február 28., szombat

PHP: Tömbök

<?php

// defining a simple array

$array1 = array(4,8,15,16,23,42);



// referencing an array value by its index

echo $array1[0];



// arrays can contain a mix of strings, numbers, even other arrays

$array2 = array(6,"fox", "dog", array("x", "y", "z"));



// referencing an array value that is inside another array

echo $array2[3][1];

?>

<br />

<?php

// Changing values in an array that has already been defined

// It's just like variables but you use the index to reference the array position

$array2[3] = "cat";

echo $array2[3];

?>

<br />

<?php

// You can also assign labels to each pocket (called "keys"),

$array3 = array("first_name" => "Kevin", "last_name" => "Skoglund");



// which will allow you to use the key to reference the value in that array position.

echo $array3["first_name"] . " " . $array3["last_name"] . "<br />";

$array3["first_name"] = "Larry";

echo $array3["first_name"] . " " . $array3["last_name"] . "<br />";

?>

<br />

A good way to see the values inside an array during development:<br />

<pre><?php print_r($array2); ?></pre>


                       

//Array Functions

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 />


            <?php

// Implode converts an array into a string using a "join string"

// Explode converts a string into an array using a "divide string"

?>

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 />

Nincsenek megjegyzések: