Forum Moderators: coopster

Message Too Old, No Replies

Best Practice : getting the first element of a string?

         

JorgeV

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

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



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!

Demaestro

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

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



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';
}
~~~

penders

10:18 pm on Oct 4, 2019 (gmt 0)

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



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.

JorgeV

11:15 pm on Oct 4, 2019 (gmt 0)

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



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.