Why is my php script not sorting an array? - php

I am trying to sort data held in a variable. I first convert it to an array then try to sort it in ascending order but it seems not to be working.
Here is my code
$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"';
$cars = (explode(",",$str));
$cars = array($cars);
sort($cars, 1);
$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br>";
}
Any workaround this?

try rsort
$str = '"10:A", "11:Q", "12:V"';
$cars = (explode(",",$str));
rsort($cars);
$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br>";
}

If you want to sort according to number try this:
<?php
function my_sort($a,$b)
{
$intval_a = filter_var($a, FILTER_SANITIZE_NUMBER_INT);
$intval_b = filter_var($b, FILTER_SANITIZE_NUMBER_INT);
if(intval($intval_a) > intval($intval_b))
return 1;
}
$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"';
$cars = explode(',',$str);
$cars = ($cars);
usort($cars, "my_sort");
$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br>";
}

There are a couple of things I've noticed. First, you've exploded the string which produces an array. You're then putting that array into another array and trying to sort that. You should remove the line $cars = array($cars);
I'd also recommend removing the quotes and spaces from the string before trying to sort them, so you are doing the sort on 10:A instead of "10:A", for example.
The other thing is the sort function should take a flag as the second parameter which defines the type of sort to perform. See the docs for the different flags you have available. I'm guessing you want it to be sorted
1:A, 2:X, 3:C...
instead of
1:A, 10:A, 11:Q...
in which case you should use the SORT_NATURAL flag. (Alternatively, you could use the natsort function).
These changes would give the following code:
$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"';
$str = str_replace(array('"', ' '), '', $str);
$cars = explode(",",$str);
sort($cars, SORT_NATURAL);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}

use natsort() function
$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"';
$cars = (explode(",",$str));
natsort($cars);
echo "<pre>"; print_r($cars);
foreach($cars as $car)
{
echo $car."<br>";
}
Check here
Hope this will help.

Related

How to replace a string by all array value using str_replace in php?

<?php
$a=array('1'=>'Jan', '2'=>'Feb','3'=>'Mar');
print_r($a);
$str ="<p>Due Month</p>";
echo str_replace("Month","(Jan+Feb+Mar)","Due Month");
?>
Desire Output:
Due (Jan+Feb+Mar)
How can I get this output from array using str_replace function?
You can try it for your desired output. It works 100%
$a = array('1'=>'Jan', '2'=>'Feb','3'=>'Mar');
print_r($a);
$comma_separated = implode("+", $a);
$str ="<p>Due Month</p>";
echo str_replace("Month","$comma_separated","Due Month");
Do you need like this?
$a = array('1'=>'Jan', '2'=>'Feb','3'=>'Mar');
$replaceStr = "";
foreach ($a as $months) {
$replaceStr[] = str_replace($months, "(Jan+Feb+Mar)", $months);
}
print_r($replaceStr);

How to skip foreach if same value?

I have loop value with code
foreach($season as $seasons){
echo $seasons->Combined_season ;
}
and the result is 0000000011111111111111111111111222222222222222222222223333333333333333333333344444444444444444444444555555555
How to skip if there same values?
I want the result is
012345
You are looking for "unique" values:
<?php
foreach($season as $seasons){
$result[] = $seasons->Combined_season;
}
echo implode('', array_unique($result));
A somewhat awkward but more memory efficient version would be this:
<?php
foreach($season as $seasons){
$result[$seasons->Combined_season] = $seasons->Combined_season;
}
echo implode('', $result);
And the most efficient variant:
<?php
foreach($season as $seasons){
$result[$seasons->Combined_season] = null;
}
echo implode('', array_keys($result));
All approaches have the advantage that they do not require a conditional in each loop iteration which makes them far more efficient for bigger input sets.
Here an update to answer your additional question:
I mentioned more than once in my comments that the variant 2 and 3 deliver what you are looking for. That you only have to use the values internally instead of imploding them for output.
The following is exactly the third approach from above, the only difference is that I did what I told you before in the comments: use the values instead of imploding them. As far as I can see it delivers exactly what you are looking for:
<?php
foreach($season as $seasons){
$result[$seasons->Combined_season] = null;
}
$value = array_keys($result);
$printedSeasons = [];
foreach($season as $seasons){
if (!in_array($seasons->Combined_season, $printedSeasons)) {
$printedSeasons[] = $seasons->Combined_season;
echo $seasons->Combined_season;
}
}
<?php
$values = [];
foreach($season as $seasons){
if(! in_array($seasons->Combined_season, $values)) {
$values[] = $seasons->Combined_season;
echo $seasons->Combined_season ;
}
}
basically, you store any new value in an array, and before printing a value, you check if it already is in that array.
Using the "array approach" is maybe the best approach. But if your results are sorted like in your example you could use an other approach, with a current value.
$curr_val = '';
foreach($season as $seasons){
if ($seasons->Combined_season != $curr_val){
echo $seasons->Combined_season ;
$curr_val = $seasons->Combined_season ;
}
}
You can use an external variable:
$old_value = '';
foreach($season as $seasons){
$new_value = $seasons->Combined_season;
if($old_value != $new_value)
{
echo $new_value;
$old_value = $new_value;
}
}

Implementing strlen() in a loop

I've got a string here with names of students (leerlingen) and im trying to follow the exercise here.
The code shows the length of the full string.
Next up would be use a loop to check who has the longest name, but how to implement strlen() in a loop?
// change the string into an array using the explode() function
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$namen = explode(" ", $sleerlingen);
echo $namen[0];
echo "<br><br>";
//determin the longest name by using a loop
// ask length
$arraylength = strlen($sleerlingen);
sleerlingen = $i;
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
echo $arraylength;
?>
You used bad separator in your explode function, in string there is no space.
This should work (I didn't try it). In foreach loop you check current length with the longest one and if the current is longer, just save it as longest.
<?php
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$names = explode(',', $sleerlingen);
$longest;
$longest_length = 0;
foreach ($names as $item) {
if (strlen($item) > $longest_length) {
$longest_length = strlen($item);
$longest = $item;
}
}
echo 'Longest name: ' . $longest . ', ' . $longest_length .' chars.';
?>
You can create a custom sort function to sort the array based on the strings length. Then you can easily take the first key in the array.
<?php
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$namen = explode(",", $sleerlingen); // changed the space to comma, otherwise it won't create an array of the string.
function sortByLength($a,$b){
return strlen($b)-strlen($a);
}
usort($namen,'sortByLength');
echo $namen[0];
?>

match two strings and compare each letter in php

I googled this question I can't to find the exact solution...
I have 2 variables...
$s1 = "ABC"; //or "BC"
$s2 = "BC"; //or "Bangalore"
I have to compare $s1 and $s2 and give the output as letters which is not present in $s2
eg : "A" // or"C"
Like that
I have to compare $s2 and $s1 and give the output as letters which is not present in $s1
eg : null // or"angalore"
What I tried..
I spit the strings to array...
Using nested for loop to find the non matched letters...
I wrote code more than 35 lines..
But no result :(
Please help me ......
echo str_ireplace(str_split($s2), "", $s1); // output: A
You can use array_diff() here:
function str_compare($str1, $str2)
{
$str1chars = str_split($str1);
$str2chars = str_split($str2);
$diff = array_diff($str1chars, $str2chars)
return implode($diff);
}
By calling the function as follows:
$diffchars = str_compare('ABC', 'BC');
You will receive a string containing the characters that do not appear in both strings. In this example, it'll be A, because that character appears in $str1, but not in $str2.
You can use str_split and array_diff like :
<?php
$s1 = 'abcedf';
$s2 = 'xzcedf5460gf';
print_r(array_diff(str_split($s1), str_split($s2)));
Use array_diff():
function str_diff($str1, $str2) {
$arr1 = str_split($str1);
$arr2 = str_split($str2);
$diff = array_diff($arr1, $arr2);
return implode($diff);
}
Usage:
echo str_diff('BC', 'Bangalore'); // => C
echo str_diff('ABC', 'BC'); // => A
Ok to do this
$str1s = "abc";
$str2s = "BCd";
function findNot($str1, $str2, $asArray = false){
$returnValue = array_diff(array_unique(str_split(strtolower($str1))), array_unique(str_split(strtolower($str2))));
if($asArray == false){
return implode($returnValue);
}else{
return $returnValue;
}
}
echo findNot($str1s, $str2s); //gives a string
echo findNot($str1s, $str2s, true); //gives array of characters
This allows you to return as either array or string.

How to put random number in array and showing this array in php

Recently I made a program to create 4 random numbers I want to put these numbers in an array but I did not echo the array's numbers :
my code is:
<?php
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
$number[i] = rand_num_generator();
}
echo $number[2];
?>
Here i am not able to access array using their index values.
You missed the $ sign in front of the i inside $number[i] which must be used before a variable
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
$number[$i] = rand_num_generator();
echo $number[$i].'<br>';
}
//print_r($number);to see the whole array
You only echo once: at echo $number[i];, $i is 4, hence you only display the last random number.
You could loop on your array to echo each.
Put your echo into loop. And you have some mistakes. Use that:
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
$number[$i] = rand_num_generator();
echo $number[$i].'<br>';
}
To put something in an array I recommend to use array_push
<?php
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
array_push($numbers, rand_num_generator());
}
print_r($numbers); //Or use 'echo $numbers[0] . " " . $numbers[1]' etc etc
?>

Categories