This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionLast revisionBoth sides next revision | ||
en:create:array [09.11.2014 15:18] – alexander.ritter | en:create:array [26.10.2018 09:54] – [Arrays] rafael.wilms | ||
---|---|---|---|
Line 37: | Line 37: | ||
<code php> | <code php> | ||
- | $a = array() | + | $a = array(); |
for ($i=0; $i<10; $i++) { | for ($i=0; $i<10; $i++) { | ||
$a[] = $i + 1; | $a[] = $i + 1; | ||
Line 171: | Line 171: | ||
'' | '' | ||
+ | |||
+ | |||
+ | ===== Associative Arrays ===== | ||
+ | |||
+ | Normal arrays are simply a list of elements. Each element has a unique position, marked by the index ('' | ||
+ | |||
+ | You create an associative array by explicitly setting the key. For assigning values to keys, PHP uses the characters '' | ||
+ | |||
+ | <code php> | ||
+ | $a = array( | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ); | ||
+ | |||
+ | $b = array( | ||
+ | 0 => ' | ||
+ | 1 => ' | ||
+ | 2 => ' | ||
+ | ); | ||
+ | </ | ||
+ | |||
+ | Yet, keys are not limited to numbers -- you may as well use strings. The next array defines the correct answers for a row of knowledge questions (question type " | ||
+ | |||
+ | <code php> | ||
+ | $c = array( | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ); | ||
+ | </ | ||
+ | |||
+ | To access thee element of an associative array, just specify the key in square brackets: | ||
+ | |||
+ | <code php> | ||
+ | $x = $c[' | ||
+ | // also possible | ||
+ | $key = ' | ||
+ | $x = $c[$key]; | ||
+ | </ | ||
+ | |||
+ | When working with associative arrays, the PHP internal function '' | ||
+ | |||
+ | <code php> | ||
+ | $c = array( | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ); | ||
+ | foreach ($c as $label=> | ||
+ | if (value($label) == $correct) { | ||
+ | html('< | ||
+ | } else { | ||
+ | html('< | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Using '' | ||
+ | |||
+ | <code php> | ||
+ | $c = array( | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ); | ||
+ | $fragen = array_keys($c); | ||
+ | for ($i=0; $i< | ||
+ | $label = $fragen[$i]; | ||
+ | $correct = $c[$label]; | ||
+ | if (value($label) == $correct) { | ||
+ | html('< | ||
+ | } else { | ||
+ | html('< | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
===== Further Array Functions ===== | ===== Further Array Functions ===== | ||
There is a whole range of further commands used for arrays. You can find a complete list in the official [[http:// | There is a whole range of further commands used for arrays. You can find a complete list in the official [[http:// |