[PHP]is_integer関数の使い方と実例解説|is_intエイリアスの完全ガイド

PHP

PHPでデータの型チェックを行う際、整数型の判定に使用される関数としてis_integer()があります。この関数はis_int()のエイリアス(別名)として提供されており、全く同じ機能を持ちます。この記事では、is_integer()関数の基本的な使い方から実践的な活用法まで、詳しく解説していきます。

is_integer関数とは?

is_integer()は、指定された変数が整数型(integer)かどうかを判定するPHPの組み込み関数です。この関数はis_int()関数のエイリアスであり、機能は完全に同じです。変数の値ではなく、データ型を厳密にチェックします。

基本的な構文

is_integer(mixed $value): bool
  • 引数: $value – 判定したい値(任意の型)
  • 戻り値: 整数型の場合はtrue、それ以外の場合はfalse
  • エイリアス: is_int()is_long()も同じ機能

エイリアス関数の関係性

PHPでは整数判定に3つの関数が提供されています:

<?php
// 以下の3つの関数は完全に同じ機能を持つ
var_dump(is_int(42));       // bool(true)
var_dump(is_integer(42));   // bool(true)
var_dump(is_long(42));      // bool(true)

// 内部的には全て同じ関数を呼び出している
$value = 42;
echo is_int($value) === is_integer($value) ? "同じ" : "異なる";        // 同じ
echo is_integer($value) === is_long($value) ? "同じ" : "異なる";       // 同じ
?>

どの関数を使うべきか?

<?php
// 推奨度の順序
function demonstrateUsagePreference() {
    $number = 42;
    
    // 1. is_int() - 最も一般的で推奨される
    if (is_int($number)) {
        echo "is_int()を使用: 推奨\n";
    }
    
    // 2. is_integer() - 可読性を重視する場合
    if (is_integer($number)) {
        echo "is_integer()を使用: 可読性重視\n";
    }
    
    // 3. is_long() - 非推奨(歴史的な理由で残存)
    if (is_long($number)) {
        echo "is_long()を使用: 非推奨\n";
    }
}

demonstrateUsagePreference();
?>

基本的な使用例

型の厳密な判定

<?php
function demonstrateStrictTyping() {
    $testValues = [
        42,          // integer
        42.0,        // float
        "42",        // string
        true,        // boolean
        null,        // null
        [42],        // array
        (object)['value' => 42] // object
    ];
    
    echo "値\t\tis_integer()\tgettype()\n";
    echo str_repeat("-", 40) . "\n";
    
    foreach ($testValues as $value) {
        printf("%-15s\t%-10s\t%s\n",
            var_export($value, true),
            is_integer($value) ? 'true' : 'false',
            gettype($value)
        );
    }
}

demonstrateStrictTyping();
?>

可読性を重視したコード例

<?php
class ReadableValidator {
    /**
     * 可読性を重視してis_integer()を使用
     */
    public static function validateUserId($userId) {
        if (!is_integer($userId)) {
            throw new InvalidArgumentException("User ID must be an integer");
        }
        
        if ($userId <= 0) {
            throw new InvalidArgumentException("User ID must be positive");
        }
        
        return true;
    }
    
    /**
     * 年齢の検証 - 自然な英語表現
     */
    public static function validateAge($age) {
        if (!is_integer($age)) {
            return [
                'valid' => false,
                'message' => 'Age must be an integer'
            ];
        }
        
        if ($age < 0 || $age > 150) {
            return [
                'valid' => false,
                'message' => 'Age must be between 0 and 150'
            ];
        }
        
        return [
            'valid' => true,
            'message' => 'Valid age'
        ];
    }
    
    /**
     * 配列のインデックス検証
     */
    public static function validateArrayIndex($index) {
        if (!is_integer($index)) {
            throw new TypeError("Array index must be an integer");
        }
        
        return $index;
    }
}

// 使用例
try {
    ReadableValidator::validateUserId(123);
    echo "User ID validation: OK\n";
    
    $ageResult = ReadableValidator::validateAge(25);
    echo "Age validation: " . $ageResult['message'] . "\n";
    
    $index = ReadableValidator::validateArrayIndex(5);
    echo "Array index validation: OK\n";
    
} catch (Exception $e) {
    echo "Validation error: " . $e->getMessage() . "\n";
}
?>

実践的な活用例

1. 設定値の検証

<?php
class ConfigurationValidator {
    private $config;
    
    public function __construct($config) {
        $this->config = $config;
        $this->validateConfiguration();
    }
    
    private function validateConfiguration() {
        $integerFields = [
            'database_port',
            'cache_ttl',
            'max_connections',
            'timeout',
            'retry_attempts'
        ];
        
        foreach ($integerFields as $field) {
            if (isset($this->config[$field])) {
                if (!is_integer($this->config[$field])) {
                    throw new InvalidArgumentException(
                        "Configuration field '{$field}' must be an integer"
                    );
                }
            }
        }
    }
    
    public function getDatabasePort() {
        return is_integer($this->config['database_port']) 
            ? $this->config['database_port'] 
            : 3306; // デフォルト値
    }
    
    public function getCacheTtl() {
        return is_integer($this->config['cache_ttl']) 
            ? $this->config['cache_ttl'] 
            : 3600; // デフォルト値
    }
}

// 使用例
$config = [
    'database_port' => 5432,
    'cache_ttl' => 1800,
    'max_connections' => 100,
    'timeout' => 30,
    'retry_attempts' => 3
];

try {
    $validator = new ConfigurationValidator($config);
    echo "Database port: " . $validator->getDatabasePort() . "\n";
    echo "Cache TTL: " . $validator->getCacheTtl() . "\n";
} catch (Exception $e) {
    echo "Configuration error: " . $e->getMessage() . "\n";
}
?>

2. 数学的計算での型安全性

<?php
class MathematicalCalculator {
    /**
     * 階乗計算(整数のみ受け付け)
     */
    public static function factorial($n) {
        if (!is_integer($n)) {
            throw new InvalidArgumentException("Factorial requires an integer input");
        }
        
        if ($n < 0) {
            throw new InvalidArgumentException("Factorial is not defined for negative integers");
        }
        
        if ($n === 0 || $n === 1) {
            return 1;
        }
        
        $result = 1;
        for ($i = 2; $i <= $n; $i++) {
            $result *= $i;
        }
        
        return $result;
    }
    
    /**
     * フィボナッチ数列(n番目の値)
     */
    public static function fibonacci($n) {
        if (!is_integer($n)) {
            throw new InvalidArgumentException("Fibonacci requires an integer position");
        }
        
        if ($n < 0) {
            throw new InvalidArgumentException("Position must be non-negative");
        }
        
        if ($n === 0) return 0;
        if ($n === 1) return 1;
        
        $a = 0;
        $b = 1;
        
        for ($i = 2; $i <= $n; $i++) {
            $temp = $a + $b;
            $a = $b;
            $b = $temp;
        }
        
        return $b;
    }
    
    /**
     * 最大公約数(ユークリッドの互除法)
     */
    public static function gcd($a, $b) {
        if (!is_integer($a) || !is_integer($b)) {
            throw new InvalidArgumentException("GCD requires integer inputs");
        }
        
        $a = abs($a);
        $b = abs($b);
        
        while ($b !== 0) {
            $temp = $b;
            $b = $a % $b;
            $a = $temp;
        }
        
        return $a;
    }
}

// 使用例
try {
    echo "5! = " . MathematicalCalculator::factorial(5) . "\n";
    echo "Fibonacci(10) = " . MathematicalCalculator::fibonacci(10) . "\n";
    echo "GCD(48, 18) = " . MathematicalCalculator::gcd(48, 18) . "\n";
} catch (Exception $e) {
    echo "Calculation error: " . $e->getMessage() . "\n";
}
?>

3. データ構造での活用

<?php
class IntegerCollection {
    private $integers = [];
    
    /**
     * 整数のみを受け付けるコレクション
     */
    public function add($value) {
        if (!is_integer($value)) {
            throw new InvalidArgumentException("Only integers can be added to this collection");
        }
        
        $this->integers[] = $value;
        return $this;
    }
    
    /**
     * 複数の整数を一度に追加
     */
    public function addMultiple(array $values) {
        foreach ($values as $value) {
            if (!is_integer($value)) {
                throw new InvalidArgumentException(
                    "All values must be integers. Found: " . gettype($value)
                );
            }
        }
        
        $this->integers = array_merge($this->integers, $values);
        return $this;
    }
    
    /**
     * 統計情報を取得
     */
    public function getStatistics() {
        if (empty($this->integers)) {
            return ['count' => 0];
        }
        
        return [
            'count' => count($this->integers),
            'sum' => array_sum($this->integers),
            'min' => min($this->integers),
            'max' => max($this->integers),
            'average' => array_sum($this->integers) / count($this->integers)
        ];
    }
    
    /**
     * 偶数のみを取得
     */
    public function getEvenNumbers() {
        return array_filter($this->integers, function($num) {
            return is_integer($num) && $num % 2 === 0;
        });
    }
    
    /**
     * 範囲内の整数を取得
     */
    public function getInRange($min, $max) {
        if (!is_integer($min) || !is_integer($max)) {
            throw new InvalidArgumentException("Range bounds must be integers");
        }
        
        return array_filter($this->integers, function($num) use ($min, $max) {
            return $num >= $min && $num <= $max;
        });
    }
}

// 使用例
try {
    $collection = new IntegerCollection();
    $collection->addMultiple([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    
    $stats = $collection->getStatistics();
    echo "Statistics: " . json_encode($stats) . "\n";
    
    $evenNumbers = $collection->getEvenNumbers();
    echo "Even numbers: " . json_encode($evenNumbers) . "\n";
    
    $inRange = $collection->getInRange(3, 7);
    echo "Numbers in range 3-7: " . json_encode($inRange) . "\n";
    
} catch (Exception $e) {
    echo "Collection error: " . $e->getMessage() . "\n";
}
?>

型変換との組み合わせ

安全な型変換

<?php
class SafeTypeConverter {
    /**
     * 安全な整数変換
     */
    public static function toInteger($value) {
        if (is_integer($value)) {
            return $value;
        }
        
        if (is_float($value)) {
            if ($value == (int)$value && !is_infinite($value) && !is_nan($value)) {
                return (int)$value;
            }
            throw new InvalidArgumentException("Float value cannot be safely converted to integer");
        }
        
        if (is_string($value)) {
            if (is_numeric($value) && (int)$value == $value) {
                return (int)$value;
            }
            throw new InvalidArgumentException("String value cannot be safely converted to integer");
        }
        
        if (is_bool($value)) {
            return (int)$value; // true -> 1, false -> 0
        }
        
        throw new InvalidArgumentException("Value cannot be converted to integer");
    }
    
    /**
     * 整数配列への変換
     */
    public static function toIntegerArray($array) {
        if (!is_array($array)) {
            throw new InvalidArgumentException("Input must be an array");
        }
        
        $result = [];
        foreach ($array as $key => $value) {
            try {
                $result[$key] = self::toInteger($value);
            } catch (InvalidArgumentException $e) {
                // 変換できない値はスキップ
                continue;
            }
        }
        
        return $result;
    }
    
    /**
     * 型検証付きの変換
     */
    public static function validateAndConvert($value, $allowedTypes = ['int', 'float', 'string']) {
        $originalType = gettype($value);
        
        if (!in_array($originalType, $allowedTypes)) {
            throw new InvalidArgumentException("Type '{$originalType}' is not allowed");
        }
        
        try {
            $converted = self::toInteger($value);
            
            return [
                'original' => $value,
                'original_type' => $originalType,
                'converted' => $converted,
                'is_integer' => is_integer($converted)
            ];
        } catch (InvalidArgumentException $e) {
            throw new InvalidArgumentException("Conversion failed: " . $e->getMessage());
        }
    }
}

// 使用例
$testValues = [42, 42.0, "42", "42.5", true, false, null, [42]];

foreach ($testValues as $value) {
    try {
        $result = SafeTypeConverter::validateAndConvert($value);
        echo "Original: " . var_export($value, true) . " -> ";
        echo "Converted: {$result['converted']} (is_integer: " . 
             ($result['is_integer'] ? 'true' : 'false') . ")\n";
    } catch (Exception $e) {
        echo "Error with " . var_export($value, true) . ": " . $e->getMessage() . "\n";
    }
}
?>

パフォーマンス考慮事項

関数選択のベンチマーク

<?php
class PerformanceBenchmark {
    public static function benchmarkAliases($iterations = 1000000) {
        $testValue = 42;
        
        // is_int()のベンチマーク
        $start = microtime(true);
        for ($i = 0; $i < $iterations; $i++) {
            is_int($testValue);
        }
        $isIntTime = microtime(true) - $start;
        
        // is_integer()のベンチマーク
        $start = microtime(true);
        for ($i = 0; $i < $iterations; $i++) {
            is_integer($testValue);
        }
        $isIntegerTime = microtime(true) - $start;
        
        // is_long()のベンチマーク
        $start = microtime(true);
        for ($i = 0; $i < $iterations; $i++) {
            is_long($testValue);
        }
        $isLongTime = microtime(true) - $start;
        
        echo "パフォーマンス比較 ({$iterations}回実行):\n";
        printf("is_int(): %.6f秒\n", $isIntTime);
        printf("is_integer(): %.6f秒\n", $isIntegerTime);
        printf("is_long(): %.6f秒\n", $isLongTime);
        
        // 差異の計算
        $avgTime = ($isIntTime + $isIntegerTime + $isLongTime) / 3;
        echo "\n差異(平均からの乖離):\n";
        printf("is_int(): %+.2f%%\n", (($isIntTime - $avgTime) / $avgTime) * 100);
        printf("is_integer(): %+.2f%%\n", (($isIntegerTime - $avgTime) / $avgTime) * 100);
        printf("is_long(): %+.2f%%\n", (($isLongTime - $avgTime) / $avgTime) * 100);
    }
}

// 実際の実行は時間がかかるため、必要に応じて実行
// PerformanceBenchmark::benchmarkAliases(100000);
?>

実用的なTips

コーディングスタイルの統一

<?php
// 良い例: 一貫したスタイル
class GoodPractice {
    private function validateIntegerInput($value, $fieldName) {
        if (!is_integer($value)) {
            throw new InvalidArgumentException("{$fieldName} must be an integer");
        }
        return $value;
    }
    
    public function processOrder($orderId, $quantity, $userId) {
        $this->validateIntegerInput($orderId, 'Order ID');
        $this->validateIntegerInput($quantity, 'Quantity');
        $this->validateIntegerInput($userId, 'User ID');
        
        // 処理続行...
    }
}

// 悪い例: 混在したスタイル
class BadPractice {
    public function processOrder($orderId, $quantity, $userId) {
        if (!is_int($orderId)) {           // is_int()使用
            throw new InvalidArgumentException("Order ID must be an integer");
        }
        
        if (!is_integer($quantity)) {      // is_integer()使用
            throw new InvalidArgumentException("Quantity must be an integer");
        }
        
        if (!is_long($userId)) {           // is_long()使用(非推奨)
            throw new InvalidArgumentException("User ID must be an integer");
        }
        
        // 処理続行...
    }
}
?>

エラーメッセージの国際化

<?php
class InternationalizedValidator {
    private $messages;
    
    public function __construct($language = 'en') {
        $this->messages = $this->loadMessages($language);
    }
    
    private function loadMessages($language) {
        $messages = [
            'en' => [
                'not_integer' => 'Value must be an integer',
                'negative_integer' => 'Value must be a positive integer',
                'out_of_range' => 'Value must be between {min} and {max}'
            ],
            'ja' => [
                'not_integer' => '値は整数である必要があります',
                'negative_integer' => '値は正の整数である必要があります',
                'out_of_range' => '値は{min}から{max}の範囲内である必要があります'
            ]
        ];
        
        return $messages[$language] ?? $messages['en'];
    }
    
    public function validateInteger($value, $min = null, $max = null) {
        if (!is_integer($value)) {
            throw new InvalidArgumentException($this->messages['not_integer']);
        }
        
        if ($min !== null && $value < $min) {
            throw new InvalidArgumentException($this->messages['negative_integer']);
        }
        
        if ($max !== null && $value > $max) {
            $message = str_replace(
                ['{min}', '{max}'],
                [$min ?? '-∞', $max ?? '+∞'],
                $this->messages['out_of_range']
            );
            throw new InvalidArgumentException($message);
        }
        
        return true;
    }
}

// 使用例
$validator_en = new InternationalizedValidator('en');
$validator_ja = new InternationalizedValidator('ja');

try {
    $validator_ja->validateInteger("123");
} catch (Exception $e) {
    echo "日本語: " . $e->getMessage() . "\n";
}

try {
    $validator_en->validateInteger("123");
} catch (Exception $e) {
    echo "English: " . $e->getMessage() . "\n";
}
?>

まとめ

is_integer()関数はis_int()の完全なエイリアスとして、整数型の厳密な判定を行います。

主な特徴

  • is_int()と完全に同じ機能: 内部的に同一の処理を実行
  • 可読性重視: 英語として自然な表現
  • 型安全性: 値ではなく型を厳密に判定

使用する場面

  • 可読性を重視するプロジェクト: 英語として自然な表現が求められる場合
  • 国際的なチーム開発: 英語圏の開発者が多い環境
  • ドキュメント重視: コードの可読性を最優先する場合

選択の指針

  • 一般的な使用: is_int()を推奨(短く一般的)
  • 可読性重視: is_integer()を選択(自然な英語表現)
  • レガシー対応: is_long()は避ける(非推奨)

どの関数を選んでも機能は同じですが、プロジェクトの方針やチームの慣習に合わせて一貫して使用することが重要です。型安全性を確保し、堅牢なPHPアプリケーションを構築するために、適切な整数判定を心がけましょう。

タイトルとURLをコピーしました