実際によく使っているphpの逆引きを掲載します
【基本】
◆コメントアウト
// コメント
/* コメント */
◆phpの情報表示
echo phpinfo();
◆functionの引数に初期値を持たせる
public static function getPresentList($sql, $userID, $viewType=array())
public static function getPresentList($sql, $userID, $viewType=true)
◆linuxからphpを実行時に引数を指定
php test.php 'aaa'
echo $argv[1];
◆コンスト(大文字アンダースコー区切り)
const USER_DATA = 'USER_DATA';
self::USER_DATA
◆複数に代入する方法
$totalPoint = $totalPointBefore = ceil($damage/100);
◆配列の中身をログに出力
error_log("GET ".print_r($_GET,true));
◆空白が少ないログ
error_log("GET ".var_export($_GET,true));
◆セッション開始
session_start();
◆セッション設定
$_SESSION['LOGIN_ID'] = 1;
◆セッション取得
$val = $_SESSION['LOGIN_ID'];
◆shellを実行する
$output = shell_exec("/var/source/current/server/sh/text.sh");
◆他のファイルを呼び出す
require_once 'Now.php';
◆スリープ1秒
sleep(1);
◆メモリー取得
echo memory_get_usage();
echo memory_get_peak_usage();
【if文】
◆値が存在するかチェック 存在する場合true
if (in_array("itme0001", $list)) {
◆リストをベタ書きで設定したのを比較 存在する場合 true
if (in_array($cardId, array(1,2,3))) {
◆キーが存在するかチェック 存在する場合true
if (array_key_exists("itme0001", $list)) {
◆ifを使わず1行で代入する場合
$nameList = (isset($nameList)) ? " - " : "";
◆空判定
if(empty($rowValue)) {
【for文】
◆foreach
foreach ($userList as $user) {
◆foreach キーを取得しながら
foreach($list as $key => $val) {
◆for
for ( $i = 0; $i < 10; $i++ ) {
◆for(10回毎)
for ( $i = 0; $i < 100; $i+=10 ) {
◆for文を抜ける
break;
◆for文で次の行を読む スキップ/コンテニュー
continue;
【配列系】
◆array初期化
$dtList = array();
◆配列に追加
array_push($userList, array('USER_ID' => '11', 'NAME' => "test"));
◆該当のキーに挿入
$dt[0] = "あああ";
◆配列と配列を一緒にする
$array1 = array_merge($array1, $array2);
◆配列から削除(除外)する
unset($outUserPartyList[$key]);
◆配列を文字列にする
implode($outList)
・配列をカンマ区切りにする
implode( ",", $outList )
◆並び変え
arsort($dtList);値の降順asort():値の昇順 ksort():昇順 krsort():降順
◆カンマ区切りを配列にする
$data='りんご,みかん,いちご,メロン,バナナ';
$dtList=explode(',',$data);
【文字列操作】
◆置き換え、置換(- ハイフンを空白にする)
str_replace("-","",$date);
◆改行文字を除外
str_replace("\n", '', $headerList[$row])
◆分割(分割する文字列、分割する文字、分割後取得する文字(splitなくなった)
preg_split("/[.]/",$_SERVER['HTTP_HOST'])[0]
◆カンマ区切り(100,000)
number_format(100000)
◆0埋め 2桁の0埋め(3→03)
sprintf('%02d', 3)
◆ランダム(1から10のランダムを取得)
mt_rand( 1, 10 );
◆文字を繰り返す ☆を10回(☆☆☆☆☆☆☆☆☆☆)
echo str_repeat("☆", 10);
◆四捨五入/切捨/切上
四捨五入 round( 数値 [, 桁数 ] ) | 切捨 floor( 数値 ) | 切上 ceil( 数値 )
(3.14→3)
round( 3.14, 0 )
【型変換】
◆stringに変換
strval(1);
◆stringをintに変換
intval('1');
◆booleanをintに変換(true1 false0)
intval(fasle);
◆stringをfloatに変換
floatval('1');
◆stringをbooleanに変換(true1 false0)
(boolean) $val['CHANGE_FLG']
◆boolを出力
var_export($testFlg);
【時間操作/日付】
◆時間 (2020/11/03 10:34:43)
date("Y/m/d H:i:s")
◆1秒前を指定
date("Y/m/d H:i:s", strtotime("-1 second" ));
◆1分前を指定
date("Y/m/d H:i:s", strtotime("-1 minute" ));
◆1時間前を指定
date("Y/m/d H:i:s", strtotime("-1 hour" ));
◆1日前を指定、
date("Y/m/d H:i:s", strtotime("-1 day" ));
◆1週間前を指定
date("Y/m/d H:i:s", strtotime("-1 week" ));
◆ミリ秒(2020-11-03 10:35:17.759)
date("Y-m-d H:i:s") . "." . substr(explode(".", (microtime(true) . ""))[1], 0, 3)
◆時間の比較
if (date('H:i:s') >= '09:00:00' && date('H:i:s') <= '15:10:00') {
◆時間に変換
date("Y/m/d H:i:s",$nowTime)
◆時間に変換
date("Y/m/d",strtotime($valUser["todo_time"]))
◆曜日 0-6で返却。0=日曜
$weekList = ['日', '月', '火', '水', '木', '金', '土',];
$week = date("w");
echo $weekList[$week];
◆月末を取得する(2020-11-30)
date('Y-m-t')
◆ゼロを付けない(2020-11-3 10:36:22)
date('Y-n-j G:i:s')
【ファイル操作】
◆全文を読み込む
$logList = file_get_contents('/var/www/html/txt/test.txt', FILE_USE_INCLUDE_PATH);
echo $logList;
◆最後の行を読み込む
$lines = array_pop(file($pathFileKawaList, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
◆ファイル書き込み
$pathFile = "/home/shell/json/msg.txt";
$fp = fopen($pathFile, 'wb');
if (flock($fp, LOCK_EX)) {
fwrite($fp, $val."\n");
flock($fp, LOCK_UN);
}
◆ファイル上書き
$fp = fopen($pathFile, 'a');
◆ファイルを書き込む(省略系)
file_put_contents("sample.txt", "HELLO WORLD");
◆ファイルを1行ずつ読む(fopenしてからfgetsをすると次呼ばれた時は呼ばれない。例えばcsvのヘッターだけ取った時など
$file = fopen("/var/www/test", "r");
while ($line = fgets($file)) {
$serverList[] = $line;
}