Tutorial :PHP explode and set to empty string the missing pieces



Question:

What's the best way to accomplish the following.

I have strings in this format:

$s1 = "name1|type1"; //(pipe is the separator)  $s2 = "name2|type2";  $s3 = "name3"; //(in some of them type can be missing)  

Let's assume nameN / typeN are strings and they can not contain a pipe.

Since I need to exctract the name / type separetly, I do:

$temp = explode('|', $s1);  $name = $temp[0];  $type = ( isset($temp[1]) ? $temp[1] : '' );  

Is there an easier (smarter whatever faster) way to do this without having to do isset($temp[1]) or count($temp).

Thanks!


Solution:1

list($name, $type) = explode('|', s1.'|');  


Solution:2

Note the order of arguments for explode()

list($name,$type) = explode( '|',$s1);  

$type will be NULL for $s3, though it will give a Notice


Solution:3

I'm a fan of array_pop() and array_shift(), which don't error out if the array they use is empty.

In your case, that would be:

$temp = explode('|', $s1);  $name = array_shift($temp);  // array_shift() will return null if the array is empty,  // so if you really want an empty string, you can string  // cast this call, as I have done:  $type = (string) array_shift($temp);  


Solution:4

There is not need to do isset since $temp[1] will exist and content an empty value. This works fine for me:

$str = 'name|type';    // if theres nothing in 'type', then $type will be empty  list($name, $type) = explode('|', $str, 2);  echo "$name, $type";  


Solution:5

if(strstr($temp,"|"))  {     $temp = explode($s1, '|');     $name = $temp[0];     $type = $temp[1];  }  else  {     $name = $temp[0];     //no type  }  

Maybe?


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »