Explode datalist into array

懵懂的女人 提交于 2020-01-06 01:47:46

问题


I've got a list of data with in the following format:

data\n
data\n
data\n
data\n
data\n

Now I try to explode it into an array with

$array = explode("\n", $dataList);

What happens next is that there is a key with no data, I think it is because of the \n on the end.

Is there a way to explode it so that the last key isn't set?

Thanks!


回答1:


After you explode, use array_pop() to pop the last item:

$array = explode("\n", $dataList);

array_pop($array);

You can add an if statement using count() and empty() if you want to check if the last item contains something other than a linebreak character, but that should get you what you need.




回答2:


Not directly. You can either:

  • Remove the trailing "\n" with trim.
  • Remove the last element of $array with array_pop.
  • Use preg_split instead with the flag PREG_SPLIT_NO_EMPTY.



回答3:


Remove empty values by:

$array = array_filter( $array );



来源:https://stackoverflow.com/questions/3347025/explode-datalist-into-array

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