To Convert String to Array in PHP Without Explode we use for loop to count the number of words on the sentence. Create a blank array to store the words which we extract using a loop in PHP.
Here is the complete example how we Convert String to Array in PHP Without Explode,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php $myString = 'This is the string to array'; $allWords = ''; $allWordsArray = array(); for($i=0; $i<strlen($myString);$i++){ if($myString[$i] == ' '){ $allWordsArray[] = $allWords; $allWords = ''; } $allWords .= $myString[$i]; } if($allWords!='') $allWordsArray[] = $allWords; echo "<pre>"; print_r($allWordsArray); |
Output:
Array
(
[0] => This
[1] => is
[2] => the
[3] => string
[4] => to
[5] => array
)
Code Explanations:
- Here we first define the string, a blank variable, and a blank array.
- A blank variable to store the extracted words from the defined string.
- Blank array to store the words which we take from the word variable and convert to an array.
- To extract the array we use for loop which loop through till the length of the string and check the spaces between the sentence.
- After taking all word into an array we print using print_r() function to print an array which looks like the above output.
How to convert string to list in PHP
To convert string to list in PHP, we use the same as above but we use list()
function. To know more about list()
the function see details https://www.php.net/manual/en/function.list.php
In this process we do below steps,
- Define a string.
- Convert that string to an array.
- That converted array changed to array list or simply list using PHP
list()
function.
Example to convert string to list in PHP
1 2 3 4 |
//add above coversion code. list($a, $b, $c, $d, $e, $f) = $allWordsArray; echo $a.$b.$c.$d.$e.$f; |
Complete code look like this,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php $myString = 'This is the string to array'; $allWords = ''; $allWordsArray = array(); for($i=0; $i<strlen($myString);$i++){ if($myString[$i] == ' '){ $allWordsArray[] = $allWords; $allWords = ''; } $allWords .= $myString[$i]; } if($allWords!='') $allWordsArray[] = $allWords; echo "<pre>"; print_r($allWordsArray); list($a, $b, $c, $d, $e, $f) = $allWordsArray; echo $a.$b.$c.$d.$e.$f; |
Output:
You can check the above complete code using our code editor online, https://codingtasks.net/php-online-editor/
If you have any doubt on this, please comment below.
Also Check:
- Get Second And Third Word from Strings in PHP
- Export MySQL Data to Excel in PHP Using Ajax
- Login with Google Account using PHP Step by Step
- How to Embed PDF in Website Using HTML
- 2 Ways to Open URL in New Tab Using JavaScript
Happy Coding..!
[…] Also Read: Convert String to Array in PHP Without Explode […]
[…] Convert String to Array in PHP Without Explode […]