H Jones
H Jones

Reputation: 47

PHP: turn array values into string variables

I have a super simple array that I need to turn into individual string/integer variables. Eg:

Array ( [0] => Array ( [0] => 35 [1] => 507 [2] => 203 ) ) 

Should result in

$value1 = 35
$value2 = 507
$value3 = 203

I'm sure this is pretty simple but I've looked at implode and it seems to concatenate the arrays into a single string, whereas I need each value as a separate variable. Have also tried foreach but come unstuck. Anyone know how to do this?

I can't seem to use $array[0][0] (=35) as I'm putting these variables into a MySQLi query and keep getting errors when I do it this way.

Thanks!

Upvotes: 0

Views: 1175

Answers (3)

H Jones
H Jones

Reputation: 47

Used extract and it works perfectly now for my query. Thanks all.

extract($array, EXTR_PREFIX_ALL, "custom");
extract($custom_0, EXTR_PREFIX_ALL, "custom2");
echo "Array item 1 is " . $custom2_0;
echo "Array item 2 is " . $custom2_1;
echo "Array item 3 is " . $custom2_2;

Upvotes: 0

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

Use php list() function like:

$arr = array( 0 => array ( 0 => 35, 1 => 507, 2 => 203 ) ) ;
list($a, $b, $c) = $arr[0];
echo $a.' : '.$b.' : '.$c;

Working Code

Php List Reference

Upvotes: 2

Alexey Chuhrov
Alexey Chuhrov

Reputation: 1787

extract($array[0], EXTR_PREFIX_ALL, "value"); 
// $value_1, $value_2, $value_3 are available

Read more: http://php.net/manual/en/function.extract.php

Upvotes: 2

Related Questions