- PHP explode() Function
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- explode
- Parameters
- Return Values
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 3 notes
- PHP explode() Function
- PHP: конвертирование массива в строку
- Использование функции implode()
- Функция explode()
- Использование функции json()
- explode
- Список параметров
- Возвращаемые значения
- Список изменений
- Примеры
- Примечания
- Смотрите также
PHP explode() Function
The explode() function breaks a string into an array.
Note: The «separator» parameter cannot be an empty string.
Note: This function is binary-safe.
Syntax
Parameter Values
Parameter | Description |
---|---|
separator | Required. Specifies where to break the string |
string | Required. The string to split |
limit | Optional. Specifies the number of array elements to return. |
- Greater than 0 — Returns an array with a maximum of limit element(s)
- Less than 0 — Returns an array except for the last -limit elements()
- 0 — Returns an array with one element
Technical Details
Return Value: | Returns an array of strings |
---|---|
PHP Version: | 4+ |
Changelog: | The limit parameter was added in PHP 4.0.1, and support for negative limits were added in PHP 5.1.0 |
More Examples
Example
Using the limit parameter to return a number of array elements:
// negative limit
print_r(explode(‘,’,$str,-1));
?>
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
explode
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator .
Parameters
If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string .
If the limit parameter is negative, all components except the last — limit are returned.
If the limit parameter is zero, then this is treated as 1.
Note:
Prior to PHP 8.0, implode() accepted its parameters in either order. explode() has never supported this: you must ensure that the separator argument comes before the string argument.
Return Values
Returns an array of string s created by splitting the string parameter on boundaries formed by the separator .
If separator is an empty string («»), explode() throws a ValueError . If separator contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned. If separator values appear at the start or end of string , said values will be added as an empty array value either in the first or last position of the returned array respectively.
Changelog
Version | Description |
---|---|
8.0.0 | explode() will now throw ValueError when separator parameter is given an empty string ( «» ). Previously, explode() returned false instead. |
Examples
Example #1 explode() examples
// Example 1
$pizza = «piece1 piece2 piece3 piece4 piece5 piece6» ;
$pieces = explode ( » » , $pizza );
echo $pieces [ 0 ]; // piece1
echo $pieces [ 1 ]; // piece2
?php
// Example 2
$data = «foo:*:1023:1000::/home/foo:/bin/sh» ;
list( $user , $pass , $uid , $gid , $gecos , $home , $shell ) = explode ( «:» , $data );
echo $user ; // foo
echo $pass ; // *
Example #2 explode() return examples
/*
A string that doesn’t contain the delimiter will simply
return a one-length array of the original string.
*/
$input1 = «hello» ;
$input2 = «hello,there» ;
$input3 = ‘,’ ;
var_dump ( explode ( ‘,’ , $input1 ) );
var_dump ( explode ( ‘,’ , $input2 ) );
var_dump ( explode ( ‘,’ , $input3 ) );
?php
The above example will output:
array(1) ( [0] => string(5) "hello" ) array(2) ( [0] => string(5) "hello" [1] => string(5) "there" ) array(2) ( [0] => string(0) "" [1] => string(0) "" )
Example #3 limit parameter examples
// positive limit
print_r ( explode ( ‘|’ , $str , 2 ));
// negative limit
print_r ( explode ( ‘|’ , $str , — 1 ));
?>
The above example will output:
Array ( [0] => one [1] => two|three|four ) Array ( [0] => one [1] => two [2] => three )
Notes
Note: This function is binary-safe.
See Also
- preg_split() — Split string by a regular expression
- str_split() — Convert a string to an array
- mb_split() — Split multibyte string using regular expression
- str_word_count() — Return information about words used in a string
- strtok() — Tokenize string
- implode() — Join array elements with a string
User Contributed Notes 3 notes
Note that an empty input string will still result in one element in the output array. This is something to remember when you are processing unknown input.
For example, maybe you are splitting part of a URI by forward slashes (like «articles/42/show» => [«articles», «42», «show»]). And maybe you expect that an empty URI will result in an empty array («» => []). Instead, it will contain one element, with an empty string:
$uri = » ;
$parts = explode ( ‘/’ , $uri );
var_dump ( $parts );
Be careful, while most non-alphanumeric data types as input strings return an array with an empty string when used with a valid separator, true returns an array with the string «1»!
var_dump(explode(‘,’, null)); //array(1) < [0]=>string(0) «» >
var_dump(explode(‘,’, false)); //array(1) < [0]=>string(0) «» >
var_dump(explode(‘,’, true)); //array(1) < [0]=>string(1) «1» >
If you want to directly take a specific value without having to store it in another variable, you can implement the following:
echo $status_only = explode(‘-‘, $status)[0];
PHP explode() Function
explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.
array explode(separator, OriginalString, NoOfElements)
Parameters : The explode function accepts three parameters of which two are compulsory and one is optional. All the three parameters are described below
- separator : This character specifies the critical points or points at which the string will split, i.e. whenever this character is found in the string it symbolizes end of one element of the array and start of another.
- OriginalString : The input string which is to be split in array.
- NoOfElements : This is optional. It is used to specify the number of elements of the array. This parameter can be any integer ( positive , negative or zero)
- Positive (N): When this parameter is passed with a positive value it means that the array will contain this number of elements. If the number of elements after separating with respect to the separator emerges to be greater than this value the first N-1 elements remain the same and the last element is the whole remaining string.
- Negative (N):If negative value is passed as parameter then the last N element of the array will be trimmed out and the remaining part of the array shall be returned as a single array.
- Zero : If this parameter is Zero then the array returned will have only one element i.e. the whole string.
Return Type: The return type of explode() function is array of strings.
Input : explode(" ","Geeks for Geeks") Output : Array ( [0] => Geeks [1] => for [2] => Geeks )
Below program illustrates the working of explode() in PHP:
PHP: конвертирование массива в строку
В этой статье разберем как преобразовывать массив в строку и обратно.
Есть два способа преобразовать массив в строку в PHP.
Использование функции implode()
Используя функцию implode(), мы можем преобразовать все элементы массива в строку. Параметр разделителя в функции implode() является необязательным. Но хорошей практикой будет использовать оба аргумента.
$arr = array("Hello", "students", " ", "how", "are", "you"); echo implode(" ", $arr);
В приведенном выше примере в первой строке объявлена переменная массива и ей присвоены некоторые значения.
На следующей строке функция implode() преобразует массив в строку. Два параметра передаются в функцию implode(). Первый — это разделитель, а второй — массив.
Вы также можете преобразовать полученную строку если требуется обратно в массив. Для этого мы можем использовать функцию PHP explode().
Функция explode()
Используя функцию explode(), мы можем преобразовать строку в элементы массива. Мы можем передать три аргумента. Первый разделитель, второй массив и последний лимит (ограничение длинны).
explode(separator, array, limit);
$str = "Hello Students, How are you"; $arr = explode(" ", $str); print_r($arr);
В приведенном выше примере строковой переменной присваивается некоторое значение. Затем функция explode() разбивает эту строку на массив. После этого мы использовали функцию print_r(), которая печатает все элементы массива и его индексы.
Использование функции json()
В PHP объекты могут быть преобразованы в строку JSON с помощью функции json_encode().
Обычное использование JSON — это чтение данных с веб-сервера и отображение данных на веб-странице.
// Присваивание значений переменной объекта @$myObj->name="Tarun"; @$myObj->age=20; @$myObj->cidy=""Noida"; $myJSON=json_encode($myObj); echo($myJSON);
В приведенном выше примере мы присвоили значение переменной объекта, а затем в json_encode() преобразовали значение в переменную массива и создали ассоциативный массив.
explode
Возвращает массив строк, полученных разбиением строки string с использованием delimiter в качестве разделителя.
Список параметров
Если аргумент limit является положительным, возвращаемый массив будет содержать максимум limit элементов, при этом последний элемент будет содержать остаток строки string .
Если параметр limit отрицателен, то будут возвращены все компоненты кроме последних — limit .
Если limit равен нулю, то он расценивается как 1.
Замечание:
По историческим причинам, функции implode() можно передавать аргументы в любом порядке, но для explode() это недопустимо. Убедитесь в том, что delimiter указан перед аргументом string .
Возвращаемые значения
Возвращает массив ( array ) строк ( string ), созданный делением параметра string по границам, указанным параметром delimiter .
Если delimiter является пустой строкой («»), explode() возвращает FALSE . Если delimiter не содержится в string , и используется отрицательный limit , то будет возвращен пустой массив ( array ), иначе будет возвращен массив, содержащий string .
Список изменений
Версия | Описание |
---|---|
5.1.0 | Добавлена поддержка отрицательных значений limit |
Примеры
Пример #1 Пример использования explode()
// Пример 1
$pizza = «кусок1 кусок2 кусок3 кусок4 кусок5 кусок6» ;
$pieces = explode ( » » , $pizza );
echo $pieces [ 0 ]; // кусок1
echo $pieces [ 1 ]; // кусок2
?php
// Пример 2
$data = «foo:*:1023:1000::/home/foo:/bin/sh» ;
list( $user , $pass , $uid , $gid , $gecos , $home , $shell ) = explode ( «:» , $data );
echo $user ; // foo
echo $pass ; // *
Пример #2 Пример возвращаемого значения explode()
/*
Строка, которая не содержит разделителя, будет
просто возвращать массив с одним значением оригинальной строки.
*/
$input1 = «hello» ;
$input2 = «hello,there» ;
var_dump ( explode ( ‘,’ , $input1 ) );
var_dump ( explode ( ‘,’ , $input2 ) );
?php
Результат выполнения данного примера:
array(1) ( [0] => string(5) "hello" ) array(2) ( [0] => string(5) "hello" [1] => string(5) "there" )
Пример #3 Примеры с использованием параметра limit
// положительный лимит
print_r ( explode ( ‘|’ , $str , 2 ));
// отрицательный лимит (начиная с PHP 5.1)
print_r ( explode ( ‘|’ , $str , — 1 ));
?>
Результат выполнения данного примера:
Array ( [0] => один [1] => два|три|четыре ) Array ( [0] => один [1] => два [2] => три )
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Смотрите также
- preg_split() — Разбивает строку по регулярному выражению
- str_split() — Преобразует строку в массив
- mb_split() — Разделение строк в многобайтных кодировках, используя регулярное выражение
- str_word_count() — Возвращает информацию о словах, входящих в строку
- strtok() — Разбивает строку на токены
- implode() — Объединяет элементы массива в строку