PHP使用explode报错:Undefined offset: 1

简介: PHP使用explode报错:Undefined offset: 1

记录下今天在使用explode进行字符串截取时出现的错误以及解决办法

错误产生


如下,字符串在截取后能够正常打印出数组

$str = "a-b-c-d";
$str_arr = explode("-", "$v");
// 输出
print_r($str_arr);
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

随后使用下标的方式给变量赋值,或者使用list赋值都会报错:Undefined offset: 1

$a = $str_arr[0];
$b = $str_arr[1];
$c = $str_arr[2];
$d = $str_arr[3];
// 或者
list($a, $b, $c, $d) = explode("-", $str);

解决办法


首先指定explode截取长度;然后使用array_pad将未定义的数组长度的值补全,这里赋值为null

list($a, $b, $c, $d) = array_pad(explode("-", $str, 4), 4, null);


目录
相关文章
|
25天前
|
PHP
PHP——oneinstack重新安装PHP的时候报错
PHP——oneinstack重新安装PHP的时候报错
34 4
|
26天前
|
PHP
PHP——安装ThinkPHP框架报错
PHP——安装ThinkPHP框架报错
12 0
|
26天前
|
JavaScript
VUE——filemanager-webpack-plugin报错TypeError: Cannot read property 'isFile' of undefined
VUE——filemanager-webpack-plugin报错TypeError: Cannot read property 'isFile' of undefined
27 0
|
2月前
|
定位技术
vue-baidu-map 报错 | map is undefined
vue-baidu-map 报错 | map is undefined
38 1
|
2月前
|
定位技术
vue-baidu-map 报错 | BMap is undefined
vue-baidu-map 报错 | BMap is undefined
45 1
|
2月前
|
JavaScript 前端开发
报错:Cannot read properties of undefined (reading ‘$message‘)解决方法
以上就是解决"Cannot read properties of undefined (reading ‘$message‘)"错误的几种方法,希望对你有所帮助。
751 0
|
3月前
|
PHP
php 使用phpize报错Cannot find config.m4. Make sure that you run ‘/usr/bin/phpize‘ in the top l
php 使用phpize报错Cannot find config.m4. Make sure that you run ‘/usr/bin/phpize‘ in the top l
161 1
|
3月前
|
关系型数据库 MySQL Serverless
函数计算操作报错合集之当遇到“Cannot read properties of undefined(reading 'props')”错误,该怎么处理
在使用函数计算服务(如阿里云函数计算)时,用户可能会遇到多种错误场景。以下是一些常见的操作报错及其可能的原因和解决方法,包括但不限于:1. 函数部署失败、2. 函数执行超时、3. 资源不足错误、4. 权限与访问错误、5. 依赖问题、6. 网络配置错误、7. 触发器配置错误、8. 日志与监控问题。
|
3月前
|
PHP 数据库
phpMyAdmin报错 in ./libraries/config/FormDisplay.php#661 continue targeting switch is equivalent to
phpMyAdmin报错 in ./libraries/config/FormDisplay.php#661 continue targeting switch is equivalent to
34 0
|
3月前
|
SQL 分布式计算 大数据
MaxCompute操作报错合集之执行sql时,出现Cannot read properties of undefined (reading 'start')错误提示,该怎么办
MaxCompute是阿里云提供的大规模离线数据处理服务,用于大数据分析、挖掘和报表生成等场景。在使用MaxCompute进行数据处理时,可能会遇到各种操作报错。以下是一些常见的MaxCompute操作报错及其可能的原因与解决措施的合集。
下一篇
DDNS