タイトル: 内部関数
SEOタイトル: PHP 内部関数 (組み込み関数) 完全リファレンス
| この記事の要点 |
|
PHP 内部関数とは
内部関数 (Internal Function / Built-in Function) は PHP 本体に組み込まれた、C 言語で実装された関数群です。strlen や array_map などが該当し、追加インストール無しで標準で利用できます。ユーザー定義関数より高速で、約 1000 個以上が用意されています。
文字列関数
// 長さ (バイト数)
strlen('hello'); // 5
strlen('こんにちは'); // 15 (UTF-8 で 1 文字 3 バイト)
// マルチバイト文字数
mb_strlen('こんにちは'); // 5 ← こちらが期待値
// 大小文字
strtoupper('Hello'); // 'HELLO'
strtolower('Hello'); // 'hello'
ucfirst('hello world'); // 'Hello world'
ucwords('hello world'); // 'Hello World'
// 部分文字列
substr('hello world', 0, 5); // 'hello'
substr('hello world', -5); // 'world' (末尾から)
mb_substr('こんにちは', 0, 2); // 'こん'
// 置換
str_replace('foo', 'bar', 'foobaz'); // 'barbaz'
str_replace(['a', 'b'], ['1', '2'], 'abc'); // '12c'
str_ireplace('FOO', 'bar', 'foobaz'); // 'barbaz' (大小無視)
// 分割・結合
explode(',', 'a,b,c'); // ['a', 'b', 'c']
implode('-', ['a', 'b', 'c']); // 'a-b-c'
// 検索
strpos('hello', 'l'); // 2 (整数 or false)
str_contains('hello', 'ell'); // true (PHP 8.0+)
str_starts_with('hello', 'he'); // true (PHP 8.0+)
str_ends_with('hello', 'lo'); // true (PHP 8.0+)
// トリム
trim(' hello '); // 'hello'
trim('"hello"', '"'); // 'hello'
ltrim(' hello '); // 'hello '
rtrim(' hello '); // ' hello'
// パディング
str_pad('5', 3, '0', STR_PAD_LEFT); // '005'
sprintf('%03d', 5); // '005'
// 正規表現
preg_match('/^[a-z]+$/', 'abc', $m); // 1, $m=['abc']
preg_match_all('/\d+/', 'a1b2c3', $m); // 3, $m=[['1','2','3']]
preg_replace('/\s+/', '-', 'a b c'); // 'a-b-c'
配列関数
// 件数
count([1, 2, 3]); // 3
count([[1, 2], [3, 4]], COUNT_RECURSIVE); // 6
// マッピング
array_map(fn($x) => $x * 2, [1, 2, 3]); // [2, 4, 6]
array_map('strtoupper', ['a', 'b']); // ['A', 'B']
array_map(null, [1, 2], ['a', 'b']); // [[1,'a'], [2,'b']] zip
// フィルタ
array_filter([1, 2, 3, 4], fn($x) => $x % 2 === 0); // [1=>2, 3=>4]
array_filter([0, 1, null, '', 'a']); // ['1', 'a'] (truthy のみ)
// 集計
array_reduce([1, 2, 3, 4], fn($acc, $x) => $acc + $x, 0); // 10
array_sum([1, 2, 3]); // 6
array_product([2, 3, 4]); // 24
max([3, 1, 4, 1, 5]); // 5
min([3, 1, 4, 1, 5]); // 1
// キー・値の操作
array_keys(['a' => 1, 'b' => 2]); // ['a', 'b']
array_values(['a' => 1, 'b' => 2]); // [1, 2]
array_flip(['a' => 1, 'b' => 2]); // [1 => 'a', 2 => 'b']
array_combine(['a', 'b'], [1, 2]); // ['a' => 1, 'b' => 2]
// 存在チェック
in_array(2, [1, 2, 3]); // true
in_array('2', [1, 2, 3], true); // false (厳密)
array_search('b', ['a', 'b', 'c']); // 1 (キー)
array_key_exists('a', ['a' => null]); // true (isset と異なる)
isset($arr['a']); // false (値が null)
// マージ・結合
array_merge([1, 2], [3, 4]); // [1, 2, 3, 4]
[...[1, 2], ...[3, 4]]; // [1, 2, 3, 4] (PHP 7.4+)
array_merge(['a' => 1], ['a' => 2]); // ['a' => 2] (後勝ち)
array_combine(['x', 'y'], [10, 20]); // ['x' => 10, 'y' => 20]
// ソート
sort($arr); // 値で昇順 (キー振り直し)
rsort($arr); // 値で降順
asort($arr); // 値で昇順 (キー維持)
ksort($arr); // キーで昇順
usort($arr, fn($a, $b) => $a['age'] <=> $b['age']); // カスタム比較
// 切り出し・結合
array_slice($arr, 1, 3); // 1番目から3個
array_splice($arr, 1, 2, ['x', 'y']); // 削除+挿入
range(1, 5); // [1, 2, 3, 4, 5]
range('a', 'e'); // ['a', 'b', 'c', 'd', 'e']
数値関数
// 丸め
round(3.5); // 4
round(3.456, 2); // 3.46
round(2.5, 0, PHP_ROUND_HALF_DOWN); // 2 (銀行家丸めも可)
ceil(3.2); // 4 (切り上げ)
floor(3.8); // 3 (切り捨て)
intval(3.7); // 3 (0方向への切り捨て)
// 絶対値・累乗・平方根
abs(-5); // 5
pow(2, 10); // 1024
2 ** 10; // 1024
sqrt(16); // 4
// 乱数
rand(1, 100); // 1〜100
mt_rand(1, 100); // メルセンヌツイスター (高速)
random_int(1, 100); // 暗号学的に安全 (★ 推奨)
random_bytes(16); // ランダムバイト列
// 数値フォーマット
number_format(1234567.891); // '1,234,568'
number_format(1234567.891, 2); // '1,234,567.89'
number_format(1234567.891, 2, '.', ' '); // '1 234 567.89'
// 数値変換
intval('42abc'); // 42
floatval('3.14abc'); // 3.14
intval('0x1A', 16); // 26 (16進)
decbin(10); // '1010'
dechex(255); // 'ff'
日時関数
// 現在時刻
time(); // Unix タイムスタンプ
date('Y-m-d H:i:s'); // '2026-06-10 12:34:56'
date('Y/m/d'); // '2026/06/10'
// 任意の時刻
date('Y-m-d', strtotime('2026-01-15')); // '2026-01-15'
date('Y-m-d', strtotime('+1 week')); // 一週間後
date('Y-m-d', strtotime('last monday')); // 直近の月曜
mktime(12, 0, 0, 6, 10, 2026); // 2026-06-10 12:00:00 のタイムスタンプ
// 差分計算
$diff = strtotime('2026-06-10') - strtotime('2026-01-01');
echo $diff / 86400 . '日';
// 推奨: DateTime クラス
$dt = new DateTime('2026-06-10 12:00:00', new DateTimeZone('Asia/Tokyo'));
$dt->modify('+3 days');
echo $dt->format('Y-m-d'); // '2026-06-13'
$diff = $dt->diff(new DateTime('2026-06-20'));
echo $diff->days; // 7
// DateTimeImmutable (副作用なし)
$dt = new DateTimeImmutable('2026-06-10');
$next = $dt->modify('+1 day'); // $dt は変更されない
ファイル関数
// 一括読み書き
$content = file_get_contents('/path/to/file.txt');
file_put_contents('/path/to/out.txt', $content);
file_put_contents('/path/to/log.txt', "log\n", FILE_APPEND | LOCK_EX);
// 1行ずつ
$lines = file('/path/to/file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// ストリーム
$fp = fopen('/path/to/file.txt', 'r');
while (($line = fgets($fp)) !== false) {
echo $line;
}
fclose($fp);
// 存在・タイプ
file_exists('/path');
is_file('/path');
is_dir('/path');
is_readable('/path');
filesize('/path/to/file');
filemtime('/path/to/file');
// CSV
$fp = fopen('/path/to/data.csv', 'r');
while (($row = fgetcsv($fp)) !== false) {
print_r($row);
}
fclose($fp);
JSON 関数
// エンコード
$json = json_encode(['name' => 'Tanaka', 'age' => 30]);
$json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
// JSON_UNESCAPED_UNICODE: 日本語をエスケープしない
// JSON_UNESCAPED_SLASHES: スラッシュをエスケープしない
// JSON_THROW_ON_ERROR: エラー時に例外 (PHP 7.3+)
// デコード
$data = json_decode($json, true); // 連想配列 で取得
$data = json_decode($json); // stdClass オブジェクト
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
// エラーチェック (古い書き方)
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception(json_last_error_msg());
}
エラー関連
// エラー出力レベル
error_reporting(E_ALL); // 全て
error_reporting(E_ALL & ~E_DEPRECATED); // DEPRECATED 以外
ini_set('display_errors', '1'); // 画面表示 (本番では Off)
ini_set('log_errors', '1'); // ログ出力
// カスタムエラー発生
trigger_error('Something wrong', E_USER_WARNING);
// エラーハンドラ
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
error_log("[$errno] $errstr in $errfile:$errline");
return true;
});
// 例外ハンドラ (未捕捉例外)
set_exception_handler(function (Throwable $e) {
error_log($e->getMessage());
});
FAQ
Q: マルチバイト文字を扱う関数の選び方は?
A: 日本語等を扱うときは mb_ 接頭辞付きを使います (mb_strlen / mb_substr / mb_strpos)。mbstring 拡張が必要で、php.ini で mbstring.internal_encoding=UTF-8 を推奨。
Q: 関数の存在確認は?
A: function_exists('foo')。古い PHP との互換コードでよく使います。
Q: 内部関数とユーザー定義関数で速度差はある?
A: 内部関数の方が C で書かれているため一般に高速。ただし PHP 8+ の JIT で差は縮まりつつあります。可読性を優先しつつ、ホットパスでは内部関数を選ぶのが基本。