Prog Web & MM Maroua BAKRI 2013-2014
Langage PHP
Correction TD N°4
Chaines de caractères, Tableaux, Fonctions
Exercice 1 :
<?php
//première méthode
$nom1=strtoupper("azerky");
$prenom1=ucfirst("sophia");
echo sprintf ("<tt>%'_-20s %'_-20s </tt><br
/>",$nom1,$prenom1);
$nom2=strtoupper("Bazertudoh");
$prenom2=ucfirst("Jean-Michel");
echo sprintf ("<tt>%'_-20s %'_-20s </tt><br
/>",$nom2,$prenom2);
?>
<?php
//deuxième méthode
$tab[0][]=strtoupper("Azerky");
$tab[0][]=ucfirst("Sophia");
$tab[1][]=strtoupper("Bazertudoh");
$tab[1][]=ucfirst("Jean-Michel");
for($i=0;$i<count($tab);$i++)
{
echo vsprintf ("<tt>%'_-20s %'_-20s </tt><br />",$tab[$i]);
}
Publicité
?>
Exercice 2 :
<?php
//1- Tableau ayant pour valeurs les entiers de 0 à 50
$tab1=range(0,50);
//2- Tableau ayant pour valeurs les décimaux de 0 à 5
foreach($tab1 as $ind=>$val)
{
$tab2[$ind]=$tab1[$ind]/10;
}
//3- Tableau dont les clés sont X et les valeurs cos(X)
1
Prog Web & MM Maroua BAKRI 2013-2014
foreach($tab2 as $ind=>$val)
{
$val= (string) $val;
$tab3[$val]= cos($val);
}
//4- Création du tableau HTML
echo "<table border=\"3\" width=\"60%\" >";
echo "<caption><b>Tableau de valeurs de la fonction
cosinus</b></caption>";
echo "<tr> <th> X </th> <th> cos( X )</th> </tr>";
foreach($tab3 as $cle=>$val)
{
echo "<tr><td>$cle</td> <td>$val</td></tr>";
Publicité
}
echo "</table>";
echo "<hr />";
?>
Exercice 3 :
Fichier somme.php
<?php
//Définition de la fonction
function SOMME($n,$d,$x)
{
$som=0;
$fact=1;
for($i=0;$i<=$n;$i++)
{
//Calcul de factorielle de $i
if($i==0) {$fact=1 ;}
else {$fact*=$i;}
//Calculde la somme
$som+= (pow($x,2*$i+1))/$fact;
//echo $som,"<br />";
}
return round($som,$d);
}
?>
Fichier ScriptPrincipal.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Publicité
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">
<title>Fonction de calcul de la somme des termes d'une suite</title>
</head>
2
Prog Web & MM Maroua BAKRI 2013-2014
<body>
<?php
include(“somme.php”);
echo SOMME(10,6,1);
?>
</body>
</html>
Exercice 4 :
<?php
Fichier Fonction.php
//Définition de la fonction
function TransTab (&$tab)
{
foreach($tab as $ind=>$val)
{
$tab[$ind]=ucfirst(strtolower($val));
}
Publicité
return $tab;
}
?>
Fichier ScriptPrincipal.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">
<title>Fonction TransTab </title>
</head>
<body>
<?php
include(‘’Fonction.php’’) ;
//Utilisation
$tabch= array("AzertToTO","Sous peAu","sARtHES jp");
echo ‘’ Tableau avant transformation : <br/> ‘’ ;
print_r($tabch);
echo ‘’<br/> Tableau après transformation : <br/> ‘’ ;
print_r(TransTab ($tabch));?>
</body>
</html>
3