1

I'm trying to get each value of an array separated in different variables.

$sql1 = "SELECT comp,code, MATCH (job) AGAINST ('$offer' IN BOOLEAN MODE) AS score FROM general_comp ORDER BY score DESC";
$result = mysqli_query($connect, $sql1);
$gen = mysqli_fetch_assoc($result);

Output: Array ( [comp] => Conseil clientèle en assurances [code] => abc [score] => 2

I'd like to have :

$comp = "Conseil clientèle en assurances";
$code = "abc";
$score = "2";
Usama Abdulrehman
  • 1,041
  • 3
  • 11
  • 21
Hymed Ghenai
  • 199
  • 15

3 Answers3

2

You can use extract

for example:

$array = array("color" => "blue",
"size"  => "medium",
"shape" => "sphere");

extract($array);

echo $color."<br>";
echo $size."<br>";
echo $shape."<br>";

this outputs:

blue
medium
sphere
xelfury
  • 203
  • 2
  • 9
  • thanks a lot, you're asnwer is the best ! what if I have several array within an array when using fetch_all 'mysqli_fetch_all($result5)' . How can I extract all the element as variables ? – Hymed Ghenai Jul 07 '20 at 16:29
1

@asjoler's answer is quite effective and succinct. But if you want secondary control over the variable names, you can use list(). array_values() is also needed to get the numerical indexes that list() needs while keeping the natural order:

$a = array();

$a["comp"] = "Conseil clientèle en assurances";
$a["code"] = "abc";
$a["score"] = 2;

list($comp, $code, $score) = array_values($a);


echo $comp . ", ";
echo $code . ", ";
echo $score;

Outputs:

Conseil clientèle en assurances
abc
2
GetSet
  • 1,511
  • 2
  • 10
  • 13
0

You can loop through your array, and convert the values to string like this:

foreach ($array as $key => $value) {
    $array[$key] = strval($value);
}

Now your arrays elements are all string.

nagyl
  • 1,644
  • 1
  • 7
  • 18
  • OP wants the values to be stored to individual variables outside of an array: `i'm trying to get each value of an array separated in different variables` – GetSet Jul 06 '20 at 21:23