オンラインPHPインタープリタ - PHPコードを即座に実行・テスト

無料のオンラインPHPインタープリタでPHPコードを即座に書いて、実行し、テストしましょう。ダウンロードやインストールは不要です。ブラウザを開いてすぐにPHPのコーディングを始められます。

💡 初心者のためのPHP基本ガイド

1. 変数と定数の宣言

PHPの変数は$で始まります。定数にはdefine()またはconstを使用します。

$x = 10;
$pi = 3.14;
$name = "Alice";
$isActive = true;

define("MAX_USERS", 100);
const APP_NAME = "CodeUtility";

2. 条件分岐 (if / switch)

分岐にはifelseifelseを使用し、複数のケースにはswitchを使用します。

$x = 2;
if ($x == 1) {
    echo "One\n";
} elseif ($x == 2) {
    echo "Two\n";
} else {
    echo "Other\n";
}

switch ($x) {
    case 1:
        echo "One\n";
        break;
    case 2:
        echo "Two\n";
        break;
    default:
        echo "Other\n";
}

3. ループ

PHPはforwhileforeachループをサポートしています。

for ($i = 0; $i < 3; $i++) {
    echo $i . "\n";
}

$n = 3;
while ($n > 0) {
    echo $n . "\n";
    $n--;
}

4. 配列

配列は複数の値を保持します。PHPはインデックス配列と連想配列をサポートしています。

$nums = array(10, 20, 30);
echo $nums[1];

5. 配列の操作

array_push()array_pop()count()、およびarray_slice()によるスライスを使用します。

$fruits = ["apple", "banana"];
array_push($fruits, "cherry");
array_pop($fruits);
print_r($fruits);

$sliced = array_slice($fruits, 0, 1);
print_r($sliced);

6. コンソール入出力

CLI入力にはreadline()を、出力にはecho/printを使用します。

$name = readline("Enter your name: ");
echo "Hello, $name\n";

7. 関数

関数は再利用可能なロジックをカプセル化します。パラメータにはデフォルト値を設定できます。

function greet($name = "Guest") {
    return "Hello, $name";
}

echo greet("Alice");

8. 連想配列

PHPの配列は文字列キーを持つ辞書のように機能します。

$person = ["name" => "Bob", "age" => 25];
echo $person["name"];

9. 例外処理

エラー処理にはtrycatchthrowを使用します。

try {
    throw new Exception("Something went wrong");
} catch (Exception $e) {
    echo $e->getMessage();
}

10. ファイル入出力

ファイル操作にはfopen()fwrite()fread()などの関数を使用します。

$file = fopen("test.txt", "w");
fwrite($file, "Hello File");
fclose($file);

$file = fopen("test.txt", "r");
echo fread($file, filesize("test.txt"));
fclose($file);

11. 文字列操作

strlen()str_replace()explode()などの関数を使用します。

$text = "Hello World";
echo strlen($text);
echo str_replace("Hello", "Hi", $text);
print_r(explode(" ", $text));

12. クラスとオブジェクト

クラスを使用して現実世界のオブジェクトをモデル化し、ロジックを再利用します。

class Person {
  public $name;
  function __construct($name) {
    $this->name = $name;
  }
  function greet() {
    return "Hi, I'm " . $this->name;
  }
}

$p = new Person("Alice");
echo $p->greet();

13. 参照

PHPでは、&を使用して変数を参照渡しできます。

function addOne(&$num) {
    $num++;
}

$x = 5;
addOne($x);
echo $x; // 6