Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 拆分字符串时强制两个数组元素的优雅方式_Php_Arrays_String - Fatal编程技术网

Php 拆分字符串时强制两个数组元素的优雅方式

Php 拆分字符串时强制两个数组元素的优雅方式,php,arrays,string,Php,Arrays,String,假设以下字符串: $string = 'entry1_entry2'; 我想做的是这样的: list($entry1, $entry2) = explode('_', $string); $string = 'entry1'; 我现在的问题是,有没有什么优雅的方法可以强制explode(或任何其他函数)获得2个数组项最小值?您可以指定第三个参数以获得最多2个元素,但我需要最小值。如果有这样一个字符串: list($entry1, $entry2) = explode('_', $strin

假设以下字符串:

$string = 'entry1_entry2';
我想做的是这样的:

list($entry1, $entry2) = explode('_', $string);
$string = 'entry1';
我现在的问题是,有没有什么优雅的方法可以强制explode(或任何其他函数)获得2个数组项最小值?您可以指定第三个参数以获得最多2个元素,但我需要最小值。如果有这样一个字符串:

list($entry1, $entry2) = explode('_', $string);
$string = 'entry1';

第二行将给出一个
通知
,因为只有一个数组元素。最好的方法是不检查结果数组或字符串是否存在分隔符。

您可能可以使用
数组\u pad

list($entry1, $entry2) = array_pad(explode('_', $string), 2, NULL);

参见

我建议将
分解
存储在多个变量中是一种糟糕的做法,因为您无法强制执行数据的完整性

你不应该只是简单地使用

$entries = explode($string);

并避免所有不必要的复杂情况?

+1,但我会使用NULL而不是空字符串作为值;谢谢,我更新了。当然,这取决于上下文,但您可能希望能够区分“foo”和“foo”…区别在于何时进行一些测试,如
isset($entry2)
,如果您将变量设置为NULL,这是错误的。谢谢,这正是您说“第二行”时我正在搜索的内容这让我想知道你是否在做这些事情
echo$array[0]$数组[1]
,只需一个foreach循环即可完全避免错误!