Welcome to WebmasterWorld Guest from 18.206.194.210

Forum Moderators: coopster & jatar k

Best Practice : getting the first element of a string?

     
4:33 pm on Oct 4, 2019 (gmt 0)

Junior Member

Top Contributors Of The Month

joined:Aug 30, 2019
posts:144
votes: 23


Hello-

I have strings, which are like that:
$str="info1|info2|info3";

So, information packed into a string, where fields are separated by the character |.

To extract the fields, I simple do:
$fields=explode("|",$str);


Now, I often only need the first field, to do so, I use this code:
echo explode("|",$str)[0];


I would like to know, if there is a "better" way to achieve the same?

Thank you!
5:41 pm on Oct 4, 2019 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month

joined:Dec 15, 2003
posts:2645
votes: 7


This is likely the best way UNLESS you want to move the pointer of the array, or remove the first item in the array.
~~~
Example:
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>
~~~

The above example will output:

~~~
Array
(
[0] => banana
[1] => apple
[2] => raspberry
)
and orange will be assigned to $fruit.
~~~

So in my example, you get the first element of the array to a variable, but it also removes it from the array.

Not sure if you would want that behavior.

If I were being picky and wanted to clean up your code

~~~
$str="info1|info2|info3";
$fields=explode("|",$str);
//make sure there is an element first
if(isset($fields[0])) {
echo $fields[0];
} else {
echo 'No Data';
}
~~~
10:18 pm on Oct 4, 2019 (gmt 0)

Senior Member

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:July 3, 2006
posts: 3153
votes: 7


Now, I often only need the first field, to do so, I use this code:


echo explode("|",$str)[0];



Or, you could do:


$str="info1|info2|info3";
// true - return string before first occurrence of "|" (exclusive)
$firstField = strstr($str,'|',true);


But note that strstr() returns (bool)false if "|" does not occur in $str.
11:15 pm on Oct 4, 2019 (gmt 0)

Junior Member

Top Contributors Of The Month

joined:Aug 30, 2019
posts:144
votes: 23


Thank you @Demaestro and @penders!

The strstr function is perfect! I didn't know about it! This is exactly what I was searching for. I found it too bad to use the explode function, which was splitting the whole string and building an array, just to get the first element. The strstr is certainly wasting way less resources. I know this is not going to drastically speed up my pages, but still.

Thank you again.