Hướng dẫn
Quảng cáo

Hàm str-split() trong PHP

Hướng dẫn cách sử dụng hàm str-split() trong lập trình PHP

Tác dụng của hàm str-split()

The str_split() function splits a string into an array of chunks.

The following table summarizes the technical details of this function.

Return Value:

Returns an array of chunks.

Returns FALSE if length is less than 1. If length exceeds the length of string, the entire string will be returned as the only element of the array.
Version: PHP 5+

Syntax

The basic syntax of the str_split() function is given with:

str_split(string, length);

The following example shows the str_split() function in action.

<?php
// Sample string
$str = "Hello World!";

// Splitting string into array
$arr = str_split($str, 2);
print_r($arr);
?>

Parameters

The str_split() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to split.
length Optional. Specifies the maximum length of each array element. Default value is 1.

More Examples

Here're some more examples showing how str_split() function actually works:

If the length parameter is not specified the string will be converted into an array of characters.

<?php
// Sample string
$str = "Hello World!";

// Breaking string into array
$arr = str_split($str);
print_r($arr);
?>

The following example shows what happens if length is set to a value larger than the string length.

<?php
// Sample string
$str = "Hello World!";

// Breaking string into array
$arr = str_split($str, 20);
print_r($arr);
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements