Page 1 of 1

turning array elements into variable

Posted: Mon Aug 13, 2007 1:31 am
by jjanes
Hi everyone,

here is the problem I have a list of words in an array

$new = array("alpha", "beta", "gamma", "delta", "epsilon");

I want to turn these words into variables
whose values are in another array
with a 1 to 1 correspondance
$test = array(1,2,3,4,5);

so that

$alpha = 1
$beta = 2
$gamma = 3
$delta = 4
$epsilon = 5

i was trying something with references in arrays but bad things happened

here is the last code snippet
:lol: :lol: :lol: Don't laugh too hard :lol: :lol: :lol:

Code: Select all

$test = array(1,2,3,4,5);
$new = array(&$alpha, &$beta, &$gamma, &$delta, &$epsilon);
for($i=0;$i=count($test);$i++) {
	new[$i] =$test[$i];
}

echo $alpha."<BR>";
echo $beta."<BR>";
echo $gamma."<BR>";
echo $delta."<BR>";
echo $epsilon."<BR>";


Any ideas or if I am going about this the wrong way what is the right way

Posted: Mon Aug 13, 2007 3:06 am
by stereofrog

Code: Select all

$vars = array("alpha", "beta", "gamma", "delta", "epsilon");
$values = array(1,2,3,4,5); 

extract(array_combine($vars, $values)); // array_combine is php5 only

echo $alpha."<BR>";
echo $beta."<BR>";
echo $gamma."<BR>";
echo $delta."<BR>";
echo $epsilon."<BR>";
You didn't explain why you need this.

Posted: Mon Aug 13, 2007 3:14 am
by Benjamin
This should do the job..

Code: Select all

<?php
$new = array("alpha", "beta", "gamma", "delta", "epsilon"); 

foreach ($new as $k => $value)
{
	$$value = ($k+1);
}

Thanks I will try these

Posted: Tue Aug 14, 2007 1:29 pm
by jjanes
Thanks I will try these out

I needed this because I want to write some functions where I can create database tables on the fly given fields
I then want to set variable with the same names as the fields supplied and then load those variables into the table.


$given = array ("field1", "field2", "field3")


set
$field1 = 1
$field2 = 2
$field3 = 3



load into a database table

insert into tablename field1, field2, field3 values ($field1, $field2 $field3)


all this can be done with a simple list of words that I can now hopefully transform into variables



Thanks

Jeff

Posted: Tue Aug 14, 2007 1:38 pm
by stereofrog
You can achieve the same using an associative array:

Code: Select all

$data = array('field1' => 1, 'field2' => 1, 'field3' => 1, );
...
insert into table field1, field2 etc values ($data[field1], $data[field2], etc
Of course, the creation of the sql statement can be easily automated.