本文目录导读:

PHP 提供了多种数据类型转换方式,我来介绍几种常用的方法:
强制类型转换(类型强制转换)
<?php // 基本类型转换 $num = "123"; $int = (int)$num; // 转整型 $float = (float)$num; // 转浮点型 $str = (string)$int; // 转字符串 $bool = (bool)$int; // 转布尔型 $array = (array)$int; // 转数组 $object = (object)$int; // 转对象 // 示例 $price = "19.99"; $price_int = (int)$price; // 19 $price_float = (float)$price; // 19.99 echo $price_int, "\n"; // 19 echo $price_float, "\n"; // 19.99 ?>
使用类型转换函数
<?php
// 类型转换函数
$value = "123.45";
$intval = intval($value); // 123
$floatval = floatval($value); // 123.45
$strval = strval($intval); // "123"
$boolval = boolval($value); // true
// 字符串处理
$hex = "ff";
$decimal = hexdec($hex); // 255(16进制转10进制)
$binary = bindec("1010"); // 10(2进制转10进制)
$octal = octdec("17"); // 15(8进制转10进制)
// 格式化数字
$number = 1234.5678;
$rounded = round($number, 2); // 1234.57
$ceil = ceil($number); // 1235(向上取整)
$floor = floor($number); // 1234(向下取整)
?>
JSON 转换
<?php
// 数组转 JSON
$data = [
'name' => 'John',
'age' => 30,
'hobbies' => ['reading', 'coding']
];
$json = json_encode($data);
echo $json; // {"name":"John","age":30,"hobbies":["reading","coding"]}
// JSON 转数组
$json_str = '{"name":"John","age":30}';
$array = json_decode($json_str, true); // 第二个参数true表示返回数组
$object = json_decode($json_str); // 默认返回对象
echo $array['name']; // John
echo $object->name; // John
// 异常处理
$invalid_json = '{"name":}';
$result = json_decode($invalid_json);
if (json_last_error() === JSON_ERROR_NONE) {
// 解析成功
} else {
echo 'JSON 解析错误: ' . json_last_error_msg();
}
?>
序列化转换
<?php
// 序列化和反序列化
$data = [
'name' => 'Mary',
'skills' => ['PHP', 'MySQL', 'JavaScript']
];
// 序列化
$serialized = serialize($data);
echo $serialized;
// a:2:{s:4:"name";s:4:"Mary";s:6:"skills";a:3:{i:0;s:3:"PHP";i:1;s:5:"MySQL";i:2;s:10:"JavaScript";}}
// 反序列化
$unserialized = unserialize($serialized);
print_r($unserialized);
// 存储到缓存
// 文件缓存
file_put_contents('cache.dat', serialize($data));
$cache = unserialize(file_get_contents('cache.dat'));
?>
字符串转换(字符串操作)
<?php
// 字符串与数组转换
$str = "apple,banana,orange";
$array = explode(",", $str); // ['apple', 'banana', 'orange']
$new_str = implode("-", $array); // "apple-banana-orange"
// 字符串与数字转换
$num_str = "42";
$num = +$num_str; // 42(一元运算符)
$num2 = $num_str + 0; // 42(加法运算)
// 字符串解析为变量
$str = "color=red&size=M";
parse_str($str, $vars); // $vars = ['color' => 'red', 'size' => 'M']
// 类型判断
$var = "123";
if (is_numeric($var)) {
$num = (int)$var; // 123
}
?>
数组转换
<?php
// 对象转数组
class Person {
public $name = "Tom";
private $age = 25;
}
$person = new Person();
$arr = (array)$person;
print_r($arr);
// 数组转对象
$data = ['name' => 'Jerry', 'age' => 28];
$obj = (object)$data;
echo $obj->name; // Jerry
// 字符串转数组
$str = "Hello World";
$chars = str_split($str); // ['H', 'e', 'l', 'l', 'o', ' ', 'W', ...]
$words = explode(" ", $str); // ['Hello', 'World']
?>
进制转换
<?php
// 不同进制转换
$number = 255;
// 十进制转其他进制
$binary = decbin($number); // "11111111"
$octal = decoct($number); // "377"
$hex = dechex($number); // "ff"
// 其他进制转十进制
$dec = hexdec("ff"); // 255
$dec2 = bindec("11111111"); // 255
$dec3 = octdec("377"); // 255
// 任意进制转换
$result = base_convert("ff", 16, 2); // 16进制转2进制 = "11111111"
?>
安全类型转换
<?php
// 类型检查和安全转换
function safeConvert($value, $type) {
switch ($type) {
case 'int':
return is_numeric($value) ? (int)$value : 0;
case 'float':
return is_numeric($value) ? (float)$value : 0.0;
case 'string':
return (string)$value;
case 'bool':
return (bool)$value;
case 'array':
return is_array($value) ? $value : [$value];
default:
return null;
}
}
// 使用
echo safeConvert("123abc", 'int'); // 123
echo safeConvert("12.5", 'float'); // 12.5
echo safeConvert("true", 'bool'); // 1 (true)
var_dump(safeConvert("test", 'array')); // array(1) { [0] => string(4) "test" }
?>
常用转换场景总结
<?php
// 表单数据处理
$form_age = "25"; // 表单返回的总是字符串
$age = (int)$form_age;
// API 响应处理
$api_response = '{"success":true,"data":[...]}';
$parsed = json_decode($api_response, true);
// 数据库结果处理
$db_value = "0123";
$numeric = (int)ltrim($db_value, '0'); // 去除前导0
// 模板输出
$price = 19.99;
$formatted = number_format($price, 2); // "19.99"
// 兼容字符串类型
if (is_string($input)) {
// 转换为大写
$upper = strtoupper($input);
}
?>
选择哪种转换方法取决于:
- 强制类型转换:快速简单,适合基本类型
- JSON:适合数据交换和API交互
- 序列化:适合PHP内部数据缓存
- 字符串函数:适合格式化和特定处理
- 安全转换:需要验证和默认值时使用
记得根据具体场景选择最合适的方式!