【PHP】これで分かる関数! – 変数操作関数その1 –

PHP

更新履歴

更新日更新者更新内容
2021/8/23JJI・”はじめに”の段落を追加
・サンプルプログラムの実行結果に画面の画像を追加

はじめに

サンプルプログラムの中で次の記事で載せている関数を使用している場合があります。

型変換

型変換でよく使用する次の関数についてサンプルプログラムを使って説明します。

関数説明(PHPマニュアル抜粋)
boolval変数の boolean としての値を取得する
floatval変数の float 値を取得する
gettype変数の型を取得する
intval変数の整数としての値を取得する
strval変数の文字列としての値を取得する
unset指定した変数の割当を解除する

サンプルプログラム

型変換の関数を使用したサンプルプログラムです。

<?php
    // 引数の値への厳密な型付け
    declare(strict_types = 1);
    // 共通ライブラリの読み込み
    require_once __DIR__ . "../../../lib/sample_common.php";

    // サンプルのクラス
    class SampleObj {
        private $num;
        private $str;
    }

    echo "ファイル名:" . basename(__FILE__) . "<br>\n";
    echo "【PHP】変数操作:型変換関数<br>\n";

    // 配列1
    $mix_ary =[true, 0, "1.5", "1", false, 12.5, "abc", null, "あああ"];

    // オブジェクト
    $sample_obj = new SampleObj();

    // 配列2
    $mix_ary2 =[true, 0, "1.5", ["1", "2"], $sample_obj, 12.5, null, "あああ"];

    echo "boolvalの処理結果:<br>\n";
    echo_array1_strcall($mix_ary, "boolval");

    echo "floatvalの処理結果:<br>\n";
    echo_array1_strcall($mix_ary, "floatval");

    echo "intvalの処理結果:<br>\n";
    echo_array1_strcall($mix_ary, "intval");

    echo "strvalの処理結果:<br>\n";
    echo_array1_strcall($mix_ary, "strval");

    echo "gettypeの処理結果:<br>\n";
    echo_array1_strcall($mix_ary2, "gettype");
    echo "<br>\n";

    // unset()関数の確認
    $str = "aaa";
    echo 'unset()の処理前:' . $str . ":<br>\n";
    
    unset($str);

    echo "unset()の処理後:";
    if(empty($str)) {
        echo '$strは未宣言です' . ":<br>\n";
    } else {
        echo $str . ":<br>\n";
    }
    
    // 第1引数の配列を第2引数の関数で出力する
    function echo_array1_strcall(array $ary, string $func) :void {
        $i = 0;

        foreach($ary as $key => $val) {
            if($i != 0) {
                echo " ";
            }
            echo "[$key]:" . $func($val) . ":";
            $i++;
        }
        echo "<br>\n";
    }
?>

実行結果です。

・画面

・HTML

ファイル名:sample02_07_01.php<br>
【PHP】変数操作:型変換関数<br>
boolvalの処理結果:<br>
[0]:1: [1]:: [2]:1: [3]:1: [4]:: [5]:1: [6]:1: [7]:: [8]:1:<br>
floatvalの処理結果:<br>
[0]:1: [1]:0: [2]:1.5: [3]:1: [4]:0: [5]:12.5: [6]:0: [7]:0: [8]:0:<br>
intvalの処理結果:<br>
[0]:1: [1]:0: [2]:1: [3]:1: [4]:0: [5]:12: [6]:0: [7]:0: [8]:0:<br>
strvalの処理結果:<br>
[0]:1: [1]:0: [2]:1.5: [3]:1: [4]:: [5]:12.5: [6]:abc: [7]:: [8]:あああ:<br>
gettypeの処理結果:<br>
[0]:boolean: [1]:integer: [2]:string: [3]:array: [4]:object: [5]:double: [6]:NULL: [7]:string:<br>
<br>
unset()の処理前:aaa:<br>
unset()の処理後:$strは未宣言です:<br>

コメント