in_array if $massive = $insteredname [closed]
<?
$nimi = $_POST['nimi'];
$nimed = $_POST['nimed'];
if ($nimi) {
if ($nimed) {
$nimed .= ', ' .$nimi;
}
else {
$nimed = $nimi;
}
}
?>
<html>
<form method="post">
Sisesta nimi:
<input type="text" name="nimi" size="9" />
<input type="hidden" name="nimed" value="<?= $nimed ?>" />
<input type="submit" value="Lisa" />
</form>
<?
$m = explode(', ',$nimed);
sort ($m);
if ($nimi) {
echo '<ol>';
foreach ($m as $nimi) {
echo "<li>$nimi<br /></li>";
}
}
echo '</ol>';
?>
</html>
E: WHERE DO I PUT IN_ARRAY SO IT WOULD SAY "THIS NAME IS ALREADY THERE INSTEAD OF ADDING IT TO THE LIST"
if (in_array($nimi,$m)) {}
I'm assuming from this that $nimi is a single name, and $nimed is the list of names submitted.
If you wanted to ensure the doubled name isn't in the list and still output, you'd check in_array before concatting the name to the list, something along the lines of
if($nimi) {
if($nimed) {
if(strpos($nimi,$nimed) === false) {
echo("THIS NAME IS ALREADY THERE INSTEAD OF ADDING IT TO THE LIST");
}
else {
$nimed .= $nimed . ', ' . $nimi;
... snip ...
Edit: The first part of the answer sucked. Removed.
$nimi = $_POST['nimi'];
$nimed = $_POST['nimed'];
$added = false;
if ($nimi) {
if ($nimed) {
$temp = explode(', ',$nimed);
if (!in_array($nimi,$temp)) {
$nimed .= ', ' .$nimi;
$added = true;
}
}
else {
$nimed = $nimi;
}
}
...
if ($nimi && !$added) {
echo 'Already in array';
}
精彩评论