I am noob in php and i need help for list this array in 3 variables.
Array ( [ram] => 2,3, [almacenamiento] => 16,32, [marca] => Huawey,Samsung, )
I want this :
$ram= "2,3,";
$almacenamiento="16,32,";
$marca="Huawey,Samsung,";
I only know list array simple with foreach()
print_r($_POST);
$result=$_POST;
foreach($result as $indice=>$valor){
print"$indice";//INDICE
print"$valor";//VALOR
}
You can just use $$ to create variables with the same name as the keys of the array, like this:
foreach($values as $key => $value) {
$$key = $value;
}
If it is a keyed array you're using
$ram = $array['ram'];
If it is a $_POST variable (form submit, could also be a $_GET)
$ram = $_POST['ram'];
Use extract to pull out the variables from the array.
$arr = Array ( "ram" => "2,3" , "almacenamiento" => "16,32" , "marca" => "Huawey,Samsung");
Extract ($arr);
Echo $ram; // "2,3"
However I usually recommend keeping the values in the array and not extracting them.
Only in rare cases is there a point of extracting the variables.
you can use the extract()
method, it will convert the array keys into values:
$arr = array ( "ram" => "2,3" , "almacenamiento" => "16,32" , "marca" => "Huawey,Samsung");
extract($arr);
echo $ram; //2,3
echo $almacenamiento; //16,32
echo $marca; //Huawey,Samsung
Here you can find more details about extract()
Here's another way that uses array destructuring (see here, too) and it works in PHP 7.1.10+:
<?php
[$ram,$almacenamiento, $marca ]= array_values(["ram" => "2,3",
"almacenamiento" => "16,32",
"marca" => "Huawey,Samsung"
]);
var_dump($ram,$almacenamiento, $marca);
see live code
One of the disadvantages of using array destructuring is that if one is not careful, one could overwrite a variable's value. The same may occur if you use extract(), unless you provide it the paramter EXTR_SKIP, as the following example illustrates:
<?php
$a = ["red"=>"rouge","blue"=>"sea","rally"=>"game","trolley"=>"SF"];
$red = "heifer";
extract($a, EXTR_SKIP);
echo "$red, $blue, $rally, $trolley
";
See live code
However, in Programming PHP by Rasmus Lerdorf et al (1st edition), one is advised to avoid potential variable conflict by using a parameter EXTR_PREFIX_SAME which affixes a user-specified prefix to extracted variables.
Lastly, you may automate generating multiple variables based on the array's values, using the list construct along with array_values(), as follows:
<?php
list($ram,$almacenamiento, $marca )= array_values(["ram" => "2,3",
"almacenamiento" => "16,32",
"marca" => "Huawey,Samsung"
]);
var_dump($ram,$almacenamiento,$marca);
See live code
With list(), one may also overwrite variables. So one should exercise care and test whether any variables already exist before using them with list(); see example here.