explode single variable in php

被刻印的时光 ゝ 提交于 2019-12-31 06:54:05

问题


Here is what i have in php :

I need to do explode the given variable

$a = "hello~world";

I need to explode as

$first = "hello";
$second = "world";

How can i do this ??

Here is what i have tried so far.

<?php
$str = "a~b";
$a = (explode("~",$str));
$b = (explode("~",$str));
echo explode('.', 'a.b');

?>

I know i did wrong. What is my mistake and how can i fix this ?


回答1:


If you know the number of variables you're expecting to get back (ie. 2 in this case) you can just assign them directly into a list:

list($first, $second) = explode('~', $a);
// $first = 'hello';
// $second = 'world';



回答2:


Explode function will return an array with "explosed" elements

So change your code as follows (if you know that only two elements will be present)

list($a, $b) = explode('~', $str); 
//You don't need to call explode one time for element.

Otherwise, if you don't know the number of elements:

$exploded_array = explode('~', $str);
foreach ($exploded_array as $element)
{
   echo $element;
}



回答3:


explode returns an array. explode will break the given string in to parts using given character(here its ~) and will return an array with the exploded parts.

$a = "hello~world";
$str_array = explode("~",$a);

$first = $str_array[0];
$second = $str_array[1];

echo $first." ".$second;



回答4:


Your code should trigger a clear error message with debug information:

Notice: Array to string conversion

... on this line:

echo explode('.', 'a.b');

... and finally print this:

Array

I suppose you would not ignore this helpful information if you'd seen it so you've probably haven't configured your PHP development box to display error messages. The simplest way is, when installing PHP, to get your php.ini file by copying php.ini-development instead of php.ini-production. If you are using a third-party build, just tweak the error_reporting and display_errors directives.

As about the error, you have to understand that arrays are complex data structures, not scalar values. You cannot print an array as-is with echo. In the development phase you can inspect it with var_dump() (like any other variable).



来源:https://stackoverflow.com/questions/26055215/explode-single-variable-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!