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?

More than 5 years have passed since last update.

PHP基礎の基礎

Posted at

学習過程の覚え書き

文字の出力

index.php
<h1><?php echo '任意の文字列'; ?></h1>

※命令の終わりには「;」をつける

変数宣言

index.php
<?php $a = 'アイウエオ'; ?>

外部ファイルを読み込む設定

index.php
<?php include('sample.php'); ?>

PHPを書くときに気をつけること

①一つのファイルに複数のPHPブロックがある場合、全てのブロックは1つのブロックと見なされる

index.php
<?php
 $str = 'ブロック1';
?>

<html>
  <head>
    <?php 
      $echo $str; //ブロック1が出力される
      $str = 'ブロック2'; //変数$strが上書きされる
    ?>
・・・

②半角スペース、タブ、開業は変数名内でなければ無視されるので書いても問題ないが、全角は「''」「""」で囲んでないとエラーになる

配列の書き方

index.php
<?php 
  $array = array(235,'これは文字列です',3.14,FALSE);//最初に入れる値が決まってないなら$array = array();でもいい
 ?>

配列への値の入れ方

index.php
<?php 
  $array = array();
  $array[] = 'アイウエオ';
  $array[2] = 235;
 ?>

配列の値の取り出し

index.php
<?php 
  $array = array();
  $array[] = 'アイウエオ';
  echo $array[0];
 ?>

連想配列

キーと値の組み合わせでもてる

index.php
<?php 
  $array = array('スイカ'=>'甘い','レモン'=>'酸っぱい','柿'=>'渋い');
 ?>

連想配列の値の挿入

[]内にキーを指定する

index.php
<?php 
  $array = array();
  $array['スイカ'] = '甘い';
 ?>

連想配列の値の取り出し

index.php
<?php 
  $array = array();
  $array['スイカ'] = '甘い';
  echo $array['スイカ'];//甘い
 ?>

条件分岐あれこれ

switch文

index.php
<?php 
 switch($num){
  case 1:
   echo '1です';
   break;
  case 2;
   echo '2です';
   break;
 }
 ?>

if文(条件分岐)

index.php

if($num == 3){
  echo $num;
}elseif($num ==5){
  echo '5です';
}

while文

index.php

$i = 0;
while($i < 1000){
  echo $i;//条件を満たしている場合に実行する処理
  $i++;
}

for文

index.php

$i = 0;
for($i = 1; $i < 1000; $i++){//左から変数の初期化,条件、ループするごとに実行する処理
  echo $i;//条件を満たしている場合に実行する処理
}

関数宣言

※関数名が同じでも引数の数が違うと別の関数として扱われる

index.php
function total($price{//priceは引数、呼び出し元で渡す必要がある
  $result = price * 1.08;
  return '価格は'.result.'円です';
})

ローカル変数とグローバル変数

index.php

$num = 200;//グローバル変数

function total($price{
  echo $num;//関数内で作られるローカル変数なので何も出力されない
  $result = price * 1.08;
})
echo total($num);//グローバル変数の$numがtotalメソッドで計算された結果の216が出力される
echo $num;//単純にグローバル変数の200が表示される。

//関数の中でグローバル変数を使用したい場合
function total($price{
  global $num;
  echo $num;//200
})
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?