PHP: Result of chunk_split as Array
Question by Compi | 2015-07-13 at 20:51
I would like to split an arbitrary string into parts of equal length using PHP. Basically, the PHP function chunk_split() is exactly what I am searching for. Up to now I have developed the following code:
$s = "ABCDEFGHI"; $res = chunk_split($s, 3); echo $res; // results in "ABC DEF GHI" - but I need an array!
However, chunk_split() is offering the sub-strings as string, but I need an array as a result! In other words, I would like to have each part of the string as an element in my array.
Is there any possibility to use or modify chunk_split() in a way that I get an array? It can open for each solution you can offer.
Related Topics
PHP: Remove all empty elements from string array
Tip | 0 Comments
JavaScript: Create and Use Arrays
Info | 0 Comments
Lazarus: Load File as Byte Array and save Byte Array as File
Tutorial | 0 Comments
Send Form Input as an Array to PHP Script
Tip | 0 Comments
PHP: Write array to individual Variables
Tutorial | 0 Comments
PHP: Fill Array with Sequence of Numbers or Characters
Tutorial | 0 Comments
Delphi/Lazarus: Show Byte Array as String of HEX Values
Tip | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
The function chunk_split() always returns a string, but you can easily write your own function that is returning an array instead.
For example, such a function can look like that:
You can use this function in the following way in order to split the string "ABCDEFG" into parts with a length of 3 characters:
In this function, first of all, we are calculating the number of expected parts and after that we are going through the parts with using substr() in order to cut out the corresponding substring to be able to add this string to the resulting array.
2015-07-13 at 22:55
Another possibility is to use chunk_split() in combination with explode().
I will give you a small example of this approach without using a function:
And here is the same packed into a function:
You can use the function chunk_split_arr() in the same way as it is described by my previous speaker.
We are using chunk_split() and we are splitting our string with the delimiter character "|". After that, we have to remove the last character with substr(), because otherwise we will get one part too much and the result. At the end, we are using explode() in order to divide the string at the delimiter and we are getting an array.
Of course, it is very important to use a character as delimiter which is not occurring otherwise within the string, because if so, explode() would also separate the string at this unintentional position.
2015-07-13 at 23:24