0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

演算子 PHP

Last updated at Posted at 2021-04-18

演算子の学習用メモ

演算子とは

演算子とは、ひとつ以上の値 (または「式」) から別の値 (や「式」) を生み出すものです。

https://www.php.net/manual/ja/language.operators.php

2 + 5 ;
1++ ;
$num = 14 ;
20 < 25 ;
'私の名前は' . ' 鈴木太郎' ;

これらの+``=``<``.は全て1つ以上の値を操活用し別の値を生み出すと言う点においてそれぞれ+は代数演算子=は代入演算子<は比較演算子.は結合演算子と呼ばれ、演算子という同じくくりになります。

また、++のように1つの値を活用する演算子を単項演算
2 + 5のように2つの値を活用する演算子を二項演算と呼びます。

代数演算子

基本的には学校で習った感覚で記述できます。

echo  3 + 7;
//10

演算子の優先順位

代数演算子は二項演算に部類されます。つまり以下のような式でも実際には1+2を計算し、その結果に+3のように左から評価されています。

echo 1 + 2 + 3; // 実際は (1 + 2) + 3
//6

詳しくはリファレンス参照
https://www.php.net/manual/ja/language.operators.precedence.php

代入演算子

左オペランドに右オペランドの式の値を設定する("得て代入する") ことを意味します。

echo $num = 7 ;
//7

「$num = 7」の演算後、$num変数から7を取得しなくても、「$num = 7」の演算結果として7という値は取得できる

// 変数から取得もできるが、、
$num = 7;
echo $num . "<br>";

// 演算結果で7が取得できるのでそのまま値として扱えます。
echo  $num = 7 . "<br>";

実行結果の値は7で同じです。
冒頭で演算子とは1つ以上の値を活用して別の値を生み出すと記述しましたが、変数から取得しなくても「$num = 7」という式そのものの演算結果として7が取得できています。

サンプル

$a = ($num = 7) + 3 ;
echo $a ;
//10

複合演算子

代入演算子は、同じ演算子というカテゴリに属する、代数演算子や結合演算子と組み合わせて使うことができます。これを「複合演算子」と呼びます。

//【A】
$int = 10;
$int += 5; //① + (代数演算子)  ② = (代入演算子) の順番で実行
echo $int . "<br>";
//15

//【B】
$string = 'おこさま';
$string .= 'メニュー'; //① . (結合演算子)  ② = (代入演算子) の順番で実行
echo $string . "<br>"
//おこさまメニュー

【A】の場合 $int = $int + 5; (【B】の場合 $string = $string + 'メニュー';)でも最終的に変数に代入される値は同じですが、
++.が○○演算子という同類であることを意識していると複合演算子での記述が理解しやすくなります。

続き

https://www.php.net/manual/ja/language.operators.comparison.php
https://www.php.net/manual/ja/language.operators.increment.php
https://www.php.net/manual/ja/language.operators.logical.php
https://www.php.net/manual/ja/language.operators.string.php
https://www.php.net/manual/ja/language.operators.array.php

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?