Question

FROM array with no key:

$array = array('apple','bee','carrot','dragon','elephant')

To

$newarray = ($apple,$bee,$carrot,$dragon,$elephant)

Why: I want to create flexible function to get fields from a mysql db, like this:

<?php
$query = "SELECT ".$array." FROM table";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
        extract($row);
        echo $newarray;
}
?>

So I could:

  • SELECT apple, bee, carrot and echo $apple, $bee and $carrot
  • SELECT bee, carrot, elephant and echo $bee, $carrot, and $elephant
  • or whatever.
Was it helpful?

Solution 2

foreach($array as $value){
    $newarray[] = ${$value};
    //Edited: maybe you'll need to reset the array after use it
    unset($newarray);
}

Got it!

Thanks all!

OTHER TIPS

Why don't you just fetch an associative array from the database and then use the key in the associative array like this:

// assume field names are 'apple', 'bee', 'carrot', etc.
while($row = mysql_fetch_assoc($result)){    
    foreach($row as $key => $value) {
        // this will set variables as $apple, $bee, $carrot, etc.
        $$key = $value;
    }
}

Of course this is not all that practical if you get more than one row in your result set, as the variables would just get overwritten.

The key to what you are wanting to do is the use of the variable variable ($$key in this case)

Oh yeah, you should also not be using mysql_* functions but rather mysqli_* or PDO.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top