$tab= array("a", "b", "c", "d");
array_push($tab, "e");
et on aura
$tab= array("a", "b", "c", "d", "e");
Par contre si je fais
array_slice($tab, "c");
l'élément "c" n'est pas supprimé. Idem si j'utilise array_shit array_pop ou array_splice.
$tab= array("a", "b", "c", "d", "e");
$indice = array_search("e");
unset($tab[$indice]);$indice = array_search("e");
unset($tab[$indice]);
je reçois l'erreur
J'ai essayéWarning: Wrong parameter count for array_search() in c:
$indice = array_search($tab, "e");
unset($tab[$indice]);
mais autre erreur
qu'est ce qui m'échappe?Warning: array_search(): Wrong datatype for second argument in c:\
$indice = array_search($tab, "e");
unset($tab[$indice]);
ça marche, mais par contre ceci
$indice = array_search($tab, "e");
$supp=unset($tab[$indice]);
me retourne un parse error, comme si on ne pouvait pas mettre unset() dans une variable. comment expliquer ça?
En passant, le tableau n'est pas réindexé après un unset. Il y aura des trous dans les indices.void unset ( mixed var [, mixed var [, mixed ...]] )
$tableau = array_values($tableau);$total= 50
$selection0 = rand(1, $total);
$selection1 = rand(1, $total);
$selection2 = rand(1, $total);
$selection3 = rand(1, $total);
Avec cette façon de faire, deux sélections peuvent avoir la même valeur.
// initialisation
$total = 15;
$nb = 4;
$selection = array();
// gestion erreur (pour éviter une boucle infinie!)
($total > $nb) or die ('ATENTION Solution impossible sans doublons');
// construction du tableau
for ($i = 0; $i < $nb ; $i++){
$rand = mt_rand (1, $total);
if (in_array($rand, $selection)){
$nb++;
}else{
$selection[] = $rand;
}
}
// affichage
echo 'Nombre d\'itérations effectuées: '.$nb.'<br><pre>';
print_r($selection);
echo '</pre>';
// initialisation
$total = 15;
$nb = 4;
$selection = array();
$valeursPossibles = range(1, $total);
// gestion erreur
($total > $nb) or die ('ATENTION Solution impossible sans doublons');
// construction du tableau
for ($i = 0; $i < $nb ; $i++){
$total--;
$rand = mt_rand(1, $total);
$tirage = array_splice($valeursPossibles, $rand, 1);
$selection[] = $tirage[0];
}
Plus élégant, peut-être, mais *beaucoup* plus lent pour des tirages sans remise sur de gros échantillons (variable $total importante).