PHP exploded and installed the missing parts on an empty string

What is the best way to accomplish the following.

I have lines in this format:

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

Suppose nameN / typeN are strings and they cannot contain a pipe.

Since I need an exctract name / type separetly , I do:

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

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

Thanks!

+7
php explode
source share
5 answers
 list($name, $type) = explode('|', s1.'|'); 
+7
source share

Note the order of arguments for explode ()

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

$ type will be NULL for $ s3, although it will give a Notification

+4
source share

I am a fan of array_pop() and array_shift() , which do not fail if the array they use is empty.

In your case, it will 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); 
+3
source share

There is no need to isset , because $ temp [1] will exist and contain 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"; 
0
source share
 if(strstr($temp,"|")) { $temp = explode($s1, '|'); $name = $temp[0]; $type = $temp[1]; } else { $name = $temp[0]; //no type } 

May be,?

-one
source share

All Articles