split() : Breaking of strings to create an array

$months="Jan, Feb, Mar, Apr, May, Jun, July, Aug, Sep, Oct, Nov,Dec";
$mn=split(",",$months);
echo "$mn[2]<br>";
echo "$mn[3]<br>";
We can break strings to form arrays. We can break by using a pattern or by regular expression. This way we can break strings to create array of string. Here is the syntax.
array split (string pattern, string string [, int limit])
We can specify ( option )the limit of breaking required.

One of the main uses is creating a month date and year from the data entered by the users. Users will enter date in one input box in mm/dd/yy format. We will use this string and break it into three parts storing month, date and year in three different variables for further processing. Here is the code how this works.

We will get the value from the form and the date entered by the user is available in variable $mytime. Where $mytime="05/13/05";
$arr=split("/",$mytime); // splitting the array 
$mm=$arr[0]; // first element of the array is month
$dd=$arr[1];  // second element is date
$yy=$arr[2]; // third element is year
From this date data we can format our date field as per our requirement. Read how the user entered date value is validated by using checkdate function.

Example: Splitting User Input

$input = "apple,banana,orange";
$fruits = explode(",", $input);
print_r($fruits);  // Output: Array ( [0] => apple [1] => banana [2] => orange )

Example: Handling Empty Strings

$input = "";
$result = explode(",", $input);
print_r($result);  // Output: Array ( [0] => "" )

Example: Comparing explode() and str_split()

$str = "PHP";
$exploded = explode(" ", $str);  // No space, so output is entire string
print_r($exploded);
echo "<br>";
$splitted = str_split($str);  // Splits by each character
print_r($splitted);
Output
Array ( [0] => PHP )
Array ( [0] => P [1] => H [2] => P )

Read how split command is used to separate domain and user id part from an email address
Read how split command is used to count number of words present in text string
String Functions explode(): Breaking string password_verify(): To match the password with user entered password
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer