Hier werden die Unterschiede zwischen zwei Versionen angezeigt.
Beide Seiten der vorigen RevisionVorhergehende ÜberarbeitungNächste Überarbeitung | Vorhergehende Überarbeitung | ||
de:create:array [12.12.2014 10:06] – admin | de:create:array [01.12.2019 11:12] (aktuell) – admin | ||
---|---|---|---|
Zeile 11: | Zeile 11: | ||
// Ein Array anlegen | // Ein Array anlegen | ||
$a = array(' | $a = array(' | ||
+ | </ | ||
+ | |||
+ | Statt der Schreibweise '' | ||
+ | |||
+ | <code php> | ||
+ | // Ein Array anlegen mit eckigen Klammern | ||
+ | $a = [' | ||
</ | </ | ||
Zeile 170: | Zeile 177: | ||
Ähnlich hilfreich sind '' | Ähnlich hilfreich sind '' | ||
+ | |||
+ | |||
+ | ===== Assoziative Arrays ===== | ||
+ | |||
+ | Gewöhnliche Arrays sind einfach eine Liste von Elementen, wobei jedes Element eine eindeutige Position hat. Diese Position wird durch den Index ('' | ||
+ | |||
+ | Bei assoziativen Arrays gibt man die Schlüssel explizit vor. In PHP wird die Zuordnung eines Wertes zu einem Schlüssel durch die Zeichenfolge '' | ||
+ | |||
+ | <code php> | ||
+ | $a = array( | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ); | ||
+ | |||
+ | $b = array( | ||
+ | 0 => ' | ||
+ | 1 => ' | ||
+ | 2 => ' | ||
+ | ); | ||
+ | </ | ||
+ | |||
+ | Aber als Schlüssel sind nicht nur Zahlen, sondern auch Strings erlaubt. Im folgenden Array wird damit z.B. für eine Reihe von Wissensfragen (vom Typ " | ||
+ | |||
+ | <code php> | ||
+ | $c = array( | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ); | ||
+ | </ | ||
+ | |||
+ | |||
+ | Um das Element eines assoziativen Arrays auszulesen, wird der Schlüssel einfach in eckigen Klammern angegeben: | ||
+ | |||
+ | <code php> | ||
+ | $x = $c[' | ||
+ | // oder auch | ||
+ | $key = ' | ||
+ | $x = $c[$key]; | ||
+ | </ | ||
+ | |||
+ | Besonders hilfreich für die Arbeit mit assoziativen Arrays ist die PHP-interne Funktion '' | ||
+ | |||
+ | <code php> | ||
+ | $c = array( | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ); | ||
+ | foreach ($c as $label=> | ||
+ | if (value($label) == $correct) { | ||
+ | html('< | ||
+ | } else { | ||
+ | html('< | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Eine reguläre FOR-Schleife kann man durch Einsatz von '' | ||
+ | |||
+ | <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('< | ||
+ | } | ||
+ | } | ||
+ | </ | ||