Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP explode and set to empty string the missing pieces

Tags:

php

explode

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!

like image 292
Marco Demaio Avatar asked May 19 '10 16:05

Marco Demaio


2 Answers

list($name, $type) = explode('|', s1.'|');
like image 150
Flavius Stef Avatar answered Sep 22 '22 19:09

Flavius Stef


Note the order of arguments for explode()

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

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

like image 25
Mark Baker Avatar answered Sep 22 '22 19:09

Mark Baker