LoginSignup
39
44

More than 5 years have passed since last update.

PHP頻出文法チートシート

Last updated at Posted at 2015-08-31

PHPの頻出文法のチートシートでも作ろうかなと。

// 同じ関数を複数回使用
printf($a);printf($b);
$f=printf;$f($a);$f($b); // print/echoは言語構造なので不可

// print
print($a);
print $a;
print$a;
echo$a;
?><?=$a;

// 文字列表示
echo "hoge";
echo hoge;
?>hoge<?

// rtrim
rtrim($a);
chop($a);

// 文字列の分割
preg_split('/,/',$a);
explode(',',$a);
split(',',$a); // PHP7で削除

// 配列の文字列化
implode($a);
join($a);

// 文字列置換
str_replace($m,$r,$a);
strtr($a,[$m=>$r]);
strtr($a,$m,$r); // 1文字の場合のみ

// 正規表現置換
$a=preg_replace($p,$r,$a); // マッチしなかった場合元の文字列
$a=preg_filter($p,$r,$a); // マッチしなかった場合NULL

// 正規表現検索
preg_match($p,$a,$m);
ereg($p,$a,$m); // PHP7で削除

// 繰り返し
foreach(range(1,100)as$i)echo$i;
for($i=1;$i<101;$i++)echo$i;
for(;$i++<100;)echo$i;
while($i++<100)echo$i;

// 繰り返しを抜ける
while(++$i<20);echo$i;
while(++$i<20)?><?=$i;

// $aならfunc
if($a)func();
$a&&func();

// $aならfunc1、それ以外はfunc2
if($a){func1();}else{func2();}
$a?func1():func2();
(func.($a?1:2))();

// $a==$bならfunc
if($a==$b)func();
$a!=$b?:func();
$a!=$b||func();
$a==$b&&func();

// $i==5ならfunc
if($i==5)func();
$i==5&&func();
$i-5||func();

// $i!=5ならfunc
if($i!=5)func();
$i!=5&&func();
$i^5&&func(); // intなら"!=" == "^"

// 4の倍数だけ何もしない
if($i%4){$j++;echo$k;}
if($i%4&&$j++)echo$k;
if($i%4)$j+=print$k; // echoは返り値を受けられない
$i%4?$j+=print$k:0;

// 小文字
lcfirst($a);
$a|~*; // *はchr(223)

// 大文字
strtoupper($a);
$a&*; // *はchr(223)、こちらは1文字の場合のみ

// 切り捨て
intval($x);
floor($x);
$x|0;

// 改行
echo"\n";
echo"
";
echo~*; // *はchr(245)

// 配列を全表示
for(;$i<count($a);)echo$a[+$i++];
for(;$b=$a[+$i++];)echo$b;
for(;printf($a[+$i++]););
foreach($a as$b)echo$b;
echo implode($a);

// if-else
if($a)a();elsif($b)b();else c();
switch(1){case $a:a();break;case $b:b();break;default:c();}
$a?a():($b?b():c());

文法募集中。

39
44
2

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
39
44