jump to navigation

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

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

sometimes u want the information in an array atored in variables that u can use in PHP statements or u need vaiables converted to array elements.

Convert array into variables:

Using the extract statement u can retrieve all the values from an array and insert each value into variables by using the key for the variable name. In other words, each array is copied into a variable named for the key.

extract($array_name);

Example:

<?php
$array_to_extract= array (“first_element” => “ABC”,
“second_element” => “DEF”, “third_element” => “GHI”);
extract($array_to_extract);

echo “After extracting the array it will gives us the following variables <br>”;
echo “First element is “, $first_element, “<br>”;
echo “Second element is “, $second_element, “<br>”;
echo “Third element is “, $third_element, “<br>”;
?>

The output:

After extracting the array it will gives us the following variables
First element is ABC
Second element is DEF
Third element is GHI

Convert variables into arrays:

Conversely, u can also convert a group of simple variables into an array using compact statemenet which copies the value from each specific variable name into an array element

$array_name= compact ($variable_name);

OR

$array_name= compact ($array_name);

in the first method u use the variable name directly, while in the second method u use an array that contains the names of the variables.

Example:

<?php

$array_index= array (“index1″,”index2″,”index3″);

$index1= “Hi!”;
$index2 = “Welcome 2 my blog”;
$index3 = “Noor”;

$array_to_compact1= compact(“index1″,”index2″,”index3″);
echo “Using the first method <br>”;
echo “<pre>”;
print_r($array_to_compact1);
echo “</pre>”;

$array_to_compact2= compact($array_index);
echo “Using the second method <br>”;
echo “<pre>”;
print_r($array_to_compact2);
echo “</pre>”;
?>

The output:

Using the first method

Array
(
    [index1] => Hi!
    [index2] => Welcome 2 my blog
    [index3] => Noor
)

Using the second method

Array
(
    [index1] => Hi!
    [index2] => Welcome 2 my blog
    [index3] => Noor
)

Comments»

1. Christian Bonato - August 13, 2009

Thanks, it made my code much more legible when having to echoing a huge array’s content.

Chris

me2blog - August 23, 2009

Glad 2 hear :) thnx 4 stopping in my blog :D

priya - November 20, 2010

heyyy… what if we wanted to convert the variables storing numeric data into an array and instead not convert it to string??


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.