fahad fahad - 3 years ago 106
PHP Question

Output the array such that

I am making a program that will output an array in ascending order BUT if there found matching number it will skip that and consider that later.
for example:
array = 2, 1, 3, 1, 5, 2;
output should be:
array = 1, 2, 3, 5, 1, 2 //first four sequence number(1,2,3,5) and then repeating number sequenced later.

Here is my code



<?php
if(isset($_POST['submit'])) {
$var = $_POST['in'];
$arr = explode(" ",$var);
sort($arr);
$size = sizeof($arr);
$arr2 = array();
$cnt=0;
$k=0;
for($i=0;$i<$size;$i++)
{
for($j=0;$j<$size;$j++) {
$k = $j + 1;
if($arr[$j] < $arr[$k]) {
$arr2[$j] = $arr[$j];
array_splice($arr,$j,1);
}
if($arr[$j] == $arr[$k]) {
continue;
$cnt++;
}
if($cnt==0) {
break;
}
}
}
foreach($arr2 as $value) {
echo " ".$value;
}
}
?>
<html>
<head></head>
<body>
<form method="post">
<h2>Enter data</h2>
<input type="text" name="in" placeholder="Enter data with spaces.."/>
<input type="submit" value="ok" name="submit"/>
</form>
</body>
</html>





It is not working. please correct the code.

Thanks

Answer Source

Please Try this:

$myArr = [] //with values 2, 1, 3, 1, 5, 2;
$tmp = $tmp2 = [];
foreach($myArr as $val){
   if(!in_array($val, $tmp)){
       $tmp[] = $val;
   }else{
       $tmp2[] = $val;
   }
}
$finalArr = array_merge($tmp, $tmp2); // your desired output
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download