LoginSignup
0
1

More than 5 years have passed since last update.

PHP基礎(3)型の変換

Last updated at Posted at 2018-10-12

キャスト

型の変換はキャストを使います。

文字列から数値に変換する例は、


<?php
$str = "10"; // $strは文字列
$num = (integer)$str; // 整数変換 
var_dump($num); // => 10
?>

数値から文字列に変換するときは、式展開の働きを利用してダブルクォーテーション(")で括ることもできます。


<?php
$num = 10; // $numは整数
$str = "$num"; // $strは文字列
$str2 = (string)$num; // $str2も文字列
var_dump($str2); // => "10"
?>

intval関数

他の方法としてintval関数を使って文字列から数値に変換することも一般的です。


<?php
$str = "12345"; 
$num = intval($str);
var_dump($num); // => 12345
?>

ただ実務的にはis_numeric関数で数値文字列かどうかを判定してからintvalした方がいいです。

<?php
$s = "1234";
if (is_numeric($s)) {
  var_dump(intval($s)); // => 1234
}
?>

<<PHP基礎(2)配列

PHP基礎(4)条件分岐>>

0
1
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
1