PHP convert string into an array

Write a program to convert the given string into an array.

Suppose the string is -

$a = 'Burch Jr, Philip H., The American establishment, Research in political economy 6(1983), 83-156';

Solution

Sometimes, arrays are not used to store information; instead, a string is used. The single values are all within the string, but are separated by a special character.

The following example convert string into array -

<?php
$csvdata = 'Burch Jr, Philip H., The American establishment, Research in political economy 6(1983), 83-156';
$a = explode(',', $csvdata);
$info = print_r($a, true);
echo "<pre>$info</pre>";
?>

The PHP function explode() creates an array out of these values, you just have to provide the character(s) at which the string needs to be split.

Output of the above code -

Array
(
    [0] => Burch Jr
    [1] =>  Philip H.
    [2] =>  The American establishment
    [3] =>  Research in political economy 6 (1983)
    [4] =>  83-156
)




Related PHP Programs for Practice

PHP - Division table program
PHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP - Password Hashing
PHP - Emoji Unicode Characters
PHP - Age calculator
PHP - Get array key
PHP - Capitalize first letter
PHP - Set Timezone
PHP - Remove duplicates from array
PHP - Calculate percentage of total
PHP - Fibonacci Series Program
PHP - Lock a file
PHP - Insert image in database




Read more articles


General Knowledge



Learn Popular Language