Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use explode and get first element in one line in PHP?

Tags:

arrays

php

$beforeDot = explode(".", $string)[0];

This is what I'm attempting to do, except that it returns syntax error. If there is a workaround for a one liner, please let me know. If this is not possible, please explain.

like image 793
user3388884 Avatar asked Apr 23 '14 20:04

user3388884


People also ask

How do you pop the first element of an array in PHP?

Answer: Use the PHP array_shift() function You can use the PHP array_shift() function to remove the first element or value from an array. The array_shift() function also returns the removed value of array. However, if the array is empty (or the variable is not an array), the returned value will be NULL .

What does explode () do in PHP?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.

How do you select the first element of an array?

There are several methods to get the first element of an array in PHP. Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse, and many more. We will discuss the different ways to access the first element of an array sequentially.


1 Answers

Use current(), to get first position after explode:

$beforeDot = current(explode(".", $string));
like image 152
abfurlan Avatar answered Sep 29 '22 06:09

abfurlan