PHP explode and implode method with example

Hello guys,

Occasionally, you may have situation where you need to save multiple values to single field. For example, form have multiple select dropdown with id values. In this situation either you create seperate table and join it with main table. There is also one simple idea that you create a string of array using specific character and save in field in same table. And when you need the data, you create array back with that seperator. This is easy way to store multiple value. You don't need to create seperate table or need to join table.

In this article, we will discuss on how you can convert array into string and string to back array. PHP has built in function for that.

implode() function

implode function joins array into single string with seperator.

Syntax

implode($seperator, $arr);

Parameter
$seperator seperator string default empty string
$arr The array which will be convert to strings

Example:

<?php

$fruits = array('banana', 'mango', 'grapes');

$string = implode(',', $fruits);

echo($string);

The string commonly said as comma seperated array.

explode() function

explode function converts string into array using specific delimiter.

Syntax

explode($separator, $string, $limit);

Parameter
$separator separator string default empty string
$string The string which will be convert to array
$limit Number that array will contain a maximum of limit elements

Example:

<?php

$location = '/var/www/html/bin';

$arr = explode('/', $location);

print_r($arr);

The above example will output:

Array
(
    [0] => 
    [1] => var
    [2] => www
    [3] => html
    [4] => bin
)

This way you can work with array and store array to table.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment