How to return the ordered value of arsort for variables?

Asked

Viewed 50 times

1

Well, my doubt is how to return the value contained within the "arsort($array);" in variables that can be used in other parts of the code. but the same being ordered as the result that appears in the "var_dump" type: $1 = 5, $2 = 10, $3 = 26, $4 = 34. I’ve tried several ways, but since I’m a beginner in php, I might be doing it wrong! I appreciate the help already!

$num1 = 10;

$num2 = 5;

$num3 = 34;

$num4 = 26;


$array = array($num1, $num2, $num3, $num4);

arsort($array);

var_dump($array);

//Código que aparece quando chamado o var_dump

array(4) {

[2]=> string(1) "5"

[1]=> string(2) "10"

[4]=> string(2) "26" 

[3]=> string(2) "34"

}
  • You tried to make a foreach to go through the array??

  • foreach($array as $value){ echo $value." <br>"; }

  • Yes, I did. But is there a way to return the individual value of each result to a different variable? or how to modify the foreach for the variables? I probably don’t know how to do it

  • yes you can number the variables, using a $i++, or else you can create an array for each variable...

1 answer

1

You can do it like this:

$num1 = 10;

$num2 = 5;

$num3 = 34;

$num4 = 26;


$array = array($num1, $num2, $num3, $num4);

$sort = arsort($array);

$nova_array = array();
$i = 0

foreach($sort as $value) {
    $nova_array[$i] = $value;
    $i++;
}

//Agora você pode usar assim:

echo $nova_array[0]; // imprime 5

echo $nova_array[1]; // imprime 10

Browser other questions tagged

You are not signed in. Login or sign up in order to post.