0.はじめに
この3項演算子、何かの暗号みたいですよね。
2つのプルダウンに表示される恐竜名のうち
各プルダウンで1匹を選んで、恐竜名の長さが長い方を$max_strとする。
一つ目のプルダウンで選択した恐竜、2つ目のプルダウンで選択した恐竜、max_strを表示する
(中途半端な意味のない)プログラム。
3項演算子を使いたいために作成したプログラム。
3項演算子の書式
(条件) ? (条件が真のときの処理) : (条件が偽の時の処理);
1.コード例(選択画面)
3kou_enzan.php
<!DOCTYPE html>
<html lang="ja">
<meta charset="utf-8">
<title>dinosor</title>
<h1>3項演算子 恐竜選択</h1>
<p>好きな恐竜を選んでね。</p>
<?php
$array_dino=['Tyrannosaurus','Velociraptor','Stegosaurus','Indoraptor','IndominusRex'];
?>
<form action="3kou_result.php" method="post">
一匹目
<select name="str0">
<?php
for($i=0;$i<count($array_dino);$i++){
echo "<option>".$array_dino[$i]."</option>";
}
?>
</select><br>
二匹目
<select name="str1">
<?php
for($i=0;$i<count($array_dino);$i++){
echo "<option>".$array_dino[$i]."</option>";
}
?>
</select>
<input type="submit" value="確定" name="btn2">
</form>
</html>
2.コード例(3項演算子結果)
3kou_result.php
<!DOCTYPE html>
<html lang="ja">
<meta charset="utf-8">
<title>dinosor</title>
<h1>3項演算子結果</h1>
<?php
$str0_select=isset($_POST['str0'])?htmlspecialchars($_POST['str0']):null;
$str1_select=isset($_POST['str1'])?htmlspecialchars($_POST['str1']):null;
$max_str = (strlen($str0_select)>strlen($str1_select)) ? $str0_select : $str1_select;
echo $str0_select.",".$str1_select."<br>";
echo "長い恐竜名は".$max_str."<br>";
?>
<form action="3kou_enzan.php" method="post">
<input type="submit" value="戻る">
</form>
</html>