Let’s see how to sort a string in alphabetical order by writing a simple PHP program. For this, we need to first convert the string into an array and then sort the array values using sort() PHP function and finally convert the array into a string and print the result.
Here is a simple PHP snippet that explains how to sort a string in alphabetical order.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $string = "hijdeafgbc"; //convert string to array $str_arr = str_split($string); //sort into alphabetical order using sort() php function sort($str_arr); //convert array to string again print implode($str_arr); ?> |
Let me write the same program with an HTML form to get the input from the user and then sort the string using PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<?php if ( isset($_POST['sortit']) ) { $string = $_POST['string']; //convert string to array $str_arr = str_split($string); //sort into alphabetical order using sort() php function sort($str_arr); $result = implode($str_arr); } ?> <!doctype html> <html lang="en"> <head> <title>PHP program to Sort a String in Alphabetical Order</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="row"> <div class="col"> <form method="post" action=""> <br><h2>PHP program to sort a string in Alphabetical order</h2><br> <div class="form-group"> <label for="string"><h4>Enter String</h4></label> <input type="text" min="0" value="<?=(isset($string)) ? $string : 'hijdeafgbc';?>" name="string" class="form-control" pattern="[a-zA-Z]*" title="Please enter only alphabets"> <small id="helpId" class="text-muted">Put a string and click the button to sort it</small> </div> <div class="form-group"> <h5>Result:<span id="res"> <?=(isset($result)) ? $result : '';?></span></h5> </div> <div class="form-group"> <button type="submit" name="sortit" class="btn btn-primary">Sort it</button> </div> </form> </div> </div> </div> </body> </html> |
You can see the demo of the above script from here: