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?

【PHP】基礎構文(変数、配列、ループ処理)

Posted at

変数の定義

変数名の前に$をつけて定義する

$変数名 = "〇〇"

変数の注意点は

  • 大文字と小文字で区別される($titleと$Titleは別の変数として判断)
  • 半角英数字、_のみ使用
  • $の直後に数字は不可

定数の定義

変数とは異なり、上書きすることはできない。

const 定数名 = 〇〇

定数名は大文字

データ型

スカラー型

  • 文字列型(string)
  • 整数型(intまたはinteger)
  • 浮動小数点型(floatまたはdouble)
  • 論理型(bool)
    trueまたはfalseのみ
例
$d=true;

複合型

  • 配列型(array)
$e=array(1,2,3);
または
$e=[1,2,3]
  • オブジェクト型(object)
    クラスのインスタンスを表す
class Person{
 public $name;
 }
 $f = new Person();
 $f ->name = "Taro";

特殊型

  • NULL型
    存在しないことを示す
$g =null;
  • リソース型(resource)
$h = fopen("file.text, "r");

データ型を調べたいとき

var_dump();

配列

基本構文

古い書き方
$content = array(データ1,データ2,データ3);
新しい書き方
$content = [データ1,データ2,データ3];

インデックス配列

$fruits = ["apple", "banana","cherry"];
echo $fruits[0]; //appleと出力

明示的にキーを指定することもできる

$number = [0 => "zero", 1=> "one"];

連想配列(キーを文字列に)

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

echo $person["name"]; //Taroと出力

要素の追加と削除

  • 末尾に追加
$colors = [];
$colors[] ="red";
$colors[] = "green";
  • キー指定で追加
Scolors["bg"] = "blue";
  • 削除
unset($colors["bg"]);

繰り返し処理(Rubyと比較)

forループ

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

for(初期化;条件;更新){}の構文

  • Ruby
for i in 0...5
  puts i
end

範囲オブジェクト0...5を使用

Whileループ

  • PHP
$i = 0;
while ($i < 5) {
    echo $i . "\n";
    $i++;
}
  • Ruby
i = 0
while i < 5
  puts i
  i += 1
end

foreachループ

  • PHP
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}
  • Ruby
fruits = ["apple", "banana", "cherry"]
fruits.each do |fruit|
  puts fruit
end

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?