Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
Next revision Both sides next revision
dvprog_11 [2020-02-06 13:46]
Daniel Viström
dvprog_11 [2020-05-07 13:26]
Daniel Viström
Line 95: Line 95:
 $y = 6; $y = 6;
 // Variablerna behöver inte ha samma namn som i funktionen.  // Variablerna behöver inte ha samma namn som i funktionen. 
-$sum = summa($x, $y) . '<br>';+$sum = summa($x, $y);
 echo $sum . '<br>';    // 10 skrivs ut. echo $sum . '<br>';    // 10 skrivs ut.
  
Line 120: Line 120:
 include 'foot.php'; include 'foot.php';
 </code> </code>
 +
 +
 +==== Exempel 3 ====
 +
 +Funktionen har i detta exempel lagts i en separat fil som heter 'array_first.php'.
 +<code php>
 +<?php
 +/*
 + * Funktion som returnerar en sträng med första
 + * tecknet från varje position i arrayen.
 + */
 +function array_first($arr){
 +    $answer = '';
 +    $i = 0;
 +    while($i < count($arr)){
 +        $answer = $answer . substr($arr[$i], 0, 1);
 +        $i++;
 +    }
 +    return $answer;
 +}
 +</code>
 +
 +Huvudprogram.
 +
 +<code php>
 +<?php
 +/*
 + * Funktioner kan läggas i en separat fil och
 + * göras tillgängliga med include.
 + */
 +include 'array_first.php';
 +
 +include 'head.php';
 +
 +$names = ['Helga', 'Emrik', 'Jean'];
 +// Direkt utskrift av det som returneras.
 +echo array_first($names) . '<br>';
 +
 +$animals = ['Panter','Apa', 'Räv', 'Kamel'];
 +// Det som returneras sparas i en variabel.
 +$svar = array_first($animals);
 +echo $svar . '<br>';
 +
 +include 'foot.php';
 +</code>
 +