swydell swydell - 1 month ago 11
PHP Question

convert string to array in php, output it and then output in ascending and descending order

I have so far I have managed to convert a string to an array in php and out put it with a foreach and an echo statement. But when I try to sort it I get an error like this:Warning: asort() expects parameter 1 to be array. In the text book I'm studying it shows an example like this: sort($array[,$compare]). I don't quite understand that. I don't want to use the print_r function. I just want to echo out the result So I've come here to ask for help. I appreciate any advice. Here is my code

<form action="list.php" method="post">
<input type="text" name="names">
<br>
<input type="submit" value="Submit">
<?php

if(!isset($name)) {$name = '';}
if(!isset($names)) {$names = '';}
if(!isset($value)) {$value = '';}
if(!isset($myarray)) {$myarray = '';}
$name = filter_input(INPUT_POST, 'name');
$names = filter_input(INPUT_POST, 'names');
$myarray = filter_input(INPUT_POST, 'myarray');
if($myarray === NULL){
$myarray = array();
}
$myarray = $names;
$name = explode(' ', $myarray);
foreach($name as $value){
echo ($value)."<br>";
}
$myarray = $names;
$name = explode(' ', $myarray);
foreach($name as $value){
echo asort($value)."<br>";
}
$myarray = $names;
$name = explode(' ', $myarray);
foreach($name as $value){
echo arsort($value)."<br>";
}
?>

Answer

First off, no need to do anything with $name here:

$name = filter_input(INPUT_POST, 'name');

Also no need to do anything with $myarray here:

$myarray = filter_input(INPUT_POST, 'myarray');

Or here:

if($myarray === NULL){
    $myarray = array();
}

Since you overwrite anything that could be in it here:

$myarray = $names;

And here you overwrite $name:

$name = explode(' ', $myarray);

No need to do this either, $myarray hasn't changed since receiving this value the last time:

$myarray = $names;

Sorting should be done on the array, not the values, and sort() is propably what you want here:

$name = asort($myarray);
foreach ($name as $value){
    echo "$value<br>";
}

And then the reverse sort:

$myarray = $names;
$name = arsort(explode(' ', $myarray));
foreach ($name as $value){
    echo "$value<br>";
}

So, for the complete code, somewhat simplified and shortened:

<form action="list.php" method="post">
<input type="text" name="names">
<br>
<input type="submit" value="Submit">
<?php

// This is the only variable you are posting
// Also doing explode here
$names = explode(' ', filter_input(INPUT_POST, 'names'));

// Store a copy of the array here so that we have the original unchanged
$myarray = $names;

// Printing out the array as is
foreach ($myarray as $value)
{
    // Double quotes to parse variables
    echo "$value<br>";
}

// Sort the array
sort($myarray);

// Print it out sorted
foreach ($myarray as $value)
{
    echo "$value<br>";
}

// Reverse the array
arsort($myarray);

// Print out again
foreach ($myarray as $value)
{
    echo "$value<br>";
}
?>
Comments