LoginSignup
0
0

More than 3 years have passed since last update.

【PHP】foreach、三項演算子

Posted at

PHPについて学習内容を備忘録としてまとめます。

foreach

配列専門のループ処理。
配列の要素が入っている分だけ繰り返し処理を行います。

例えば、実行例としては下記のようになります。


<?php
$test=array("test1","test2","test3");
foreach($test as $value){
print $value."<br>";
}
?>

#実行結果
test1
test2
test3

このように3つの要素を繰り返し処理しました。

連想配列

連想配列でも同様の処理をすることが可能であり、
下記のように動作します。


<?php
$test = array(test1 => test01 ,test2 => test02,” test3 => test03);
foreach($test as $key => $value){
print $value .  . $key . です<br>;
}
?>

#実行結果
test1はtest01です
test2はtest02です
test3はtest03です

三項演算子

演算対象であるオペランド(被演算子)を3つとり、?と:を以下の形式で使用します。
下記は三項演算子の実行例になります。


$val = 120;
$result = $val > 100 ? '100より大きい' : '100以下';
print $result;

先ほどの三項演算子はif文で表すと以下のようになります。


$val = 120;
if( $val > 100 ){
    print '100より大きい';
}else{
    print '100以下';
}

参考URL

https://blog-and-destroy.com/7118
https://techacademy.jp/magazine/4978

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0