jump to navigation

converting arrays into strings (and vice versa) September 17, 2008

Posted by me2blog in PHP Arrays, Variables and Data, php.
Tags: , , , , , ,
trackback

You can easily converte between arrays and strings, i.e.. u can ‘ve a sentence with each word of it in an array element!

Convert string into array:

u can create an array that contains the contents of a string by using this statement:

$array_name= explode(“s”,String);

  • s: Is the character to use to divide the string
  • String: string itself

Example:

<?php
$string_variable= “Hi:and:welcome:to:my:blog”;
$array_string = explode (“:”,$string_variable);

echo “Now lets print our new array <br>”;
echo “<pre>”;
print_r($array_string );
echo “</pre>”;
?>

The output:

Now lets print our new array

Array
(
    [0] => Hi
    [1] => and
    [2] => welcome
    [3] => to
    [4] => my
    [5] => blog
)

Convert array into a string:

Conversely, u can convert an array into string using:

$variable_name= implode (“s”,$array_name);

s: seprating the text from each array element and then store the string the $variable_name

Example:

<?php

$array_to_be_string= array (“hi”, “and”, “welcome”, “to”, “my”, “blog”);
$string_array= implode (” “,$array_to_be_string);

echo “The new string is <br>”, $string_array;
?>
The output:


The new string is
hi and welcome to my blog

Note: both emplode and implode doensn’t affect the input to the statmentm it just read it !

Comments»

1. Rob E - October 1, 2008

Thanks for sharing!

2. Andy Potanin - October 8, 2008

I think the function is called “explode” not “emplode”

$array_name= explode(ā€œsā€,String);

not

$array_name= emplode(ā€œsā€,String);

right?

3. me2blog - October 9, 2008

Yah rite
Thnx 4 telling me it’s a typing mistake …
I will correct it above …
Many many many thnx 4 u :D