Whats wrong with this array sorting - php

Here is my code :
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b-1);$i++)
{
for($j=1;$j<($b);$j++)
{
if($a[$j]<$a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
I just want to know what's wrong in the above code ? because if i take 3 array values it works fine but for 4 its not working....can someone do the modification for the same code,and also please briefly explain why is it not working any issues with looping?I am not looking for different code.

You have mistakenly modified the bubble sort algorithm. Use standard one.
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++) //Changes over here
{
for($j=0;$j<($b);$j++) //Changes over here
{
if($a[$j]>$a[$i]) //Changes over here
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}

Why are you manually sorting when you have sort?
$a = array(10,8,6,5);
sort($a);
var_dump($a);
Similarly, why are you using temporary variables when you have list?
list($a[$i],$a[$j]) = array($a[$j],$a[$i]);

try below code may be that will help.
<?php
function pr($array = array())
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$a = array(10,8,6,5);
$b = count($a);
for($i=0;$i <= ($b-1);$i++)
{
for($j=0; $j < ($b);$j++)
{
if($a[$j] < $a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
pr($temp);
pr($a);
?>

<?php
$a=array(8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++)
{
for($j=0;$j<($b);$j++)
{
if($a[$j]<$a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}

The inner loop doesn't need to be executed n times (where n=number of elements to be sorted). Every time the outer loop executes, one more element at the end (for ascending order) is in the correct position. So, inner loop should not check those elements.
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++){
for($j=0;$j<($b-$i);$j++){ // this change will save time
if($a[$j]>$a[$i]){
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
?>

Related

How to convert $_SESSION['myarray'] to regular PHP array

So I have declared a Session array and initialized it with zeroes. It's basically a multidimensional array. However, I'm thinking of converting it to a regular array because everytime I test whether a value exists or not using the in_array() function, it fails. It keeps adding existing values.
<?php
session_start();
$_SESSION['numbers'] = array(
array(0,0,0,0,0), //row1
array(0,0,0,0,0), //row2
array(0,0,0,0,0), //row3
array(0,0,0,0,0), //row4
array(0,0,0,0,0) //row5
);
?>
<?php
if (isset($_POST["num"]) && !empty($_POST["num"])){
$userInput = $_POST["num"];
for($r = 0; $r<sizeof($_SESSION['numbers']); $r++){
for($c = 0; $c<sizeof($_SESSION['numbers']); $c++){
$colVal = $_SESSION['numbers'][$r][$c];
insertInputAt($r,$c,$userInput);
}
}
}
function insertInputAt($row,$col,$input){
if(!in_array($input, $_SESSION['numbers'])){ //this fails
echo $input . "<br/>";
$_SESSION['numbers'][$row][$col] = $input;
}
}
?>
If I enter lets say 5, it inserts the input 5 to all rows and columns. I get 25 echos of value of 5 even if I put a !in_array() condition
I thought maybe if I parse the $_SESSION['numbers] as a regular array within the insertInputAt() method, the !in_array() condition might work accurately.
Thank you.
Modify your insertInputAt function to this:
function insertInputAt($row,$col,$input){
if(!in_array($input, $_SESSION['numbers'][$row])){ //this fails
echo $input . "<br/>";
$_SESSION['numbers'][$row][$col] = $input;
}
}
First of all, you do not need to initialize $_SESSION['numbers'].
<?php
session_start();
$userInput = $_POST["num"] = 1;
for($r=0;$r<count($_SESSION['numbers']);$r++){
$found = 0;
for($c=0;$c<count($_SESSION['numbers'][$r]);$c++){
if(($_SESSION['numbers'][$r][$c]==0)&&(myfunction($_SESSION['numbers'],$userInput)==0)){
$_SESSION['numbers'][$r][$c] = $userInput;unset($_POST['num']); $found=1;break;
}
}
if($found==1)break;
}
function myfunction($array,$value){
foreach($array as $q){
if(!in_array($value,$q)){
for($i=0;$i<count($q);$i++){
if($q[$i]==0) return false;
}
}
}
}
echo "<pre>";print_r($_SESSION['numbers']);
?>

PHP testing for a next item

I can't figure out how to test if there's a next item in my array by using the key to test against. I think this is better explained in code. I know there's an easier way, I'm just a noob!
Basically I want to know if there is another item in the array and if so get the ->comp_id value.
for($i=0; $i<count($allcomps); $i++)
{
if($allcomps[$i]->comp_id == $curCompID)
{
$currentIndex = $i;
if($allcomps[$i+1]->comp_id == null )
{
echo "there isn't a next";
}
//echo $allcomps[$currentIndex+1]->comp_id;
}
}
You're already looping through allcomps, so why do you need a check for the next one?
Why not check within the loop?
for($i=0; $i<count($allcomps); $i++) {
if (isset($allcomps[$i]->comp_id) and $allcomps[$i]->comp_id == $curCompID) {
$currentIndex = $i;
}
}
I think a foreach might be even easier:
foreach($allcomps as $i=>$comp) {
if (isset($comp->comp_id) and $comp->comp_id == $curCompID) {
$currentIndex = $i;
}
}

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
?>

loop problem with goto in php

I have programmed a script with the goto command but on the server where I want to execute the script there is a previous PHP version (<5.3), so I have to change the code. The structure of the code goes like that:
for($i = 0; $i < 30; $i++) // print 30 articles
{
$x = 0;
// choose a a feed from the db
// parse it
a:
foreach($feed->get_items($x, 1) as $item)
{
// create a unique id for the article of the feed
if($id == $dbid)
{
// if this id exists in the db, take the next article of the same feed which is not in the db
$x++;
goto a;
}
else
{
// print the original article you grabbed
}
} // end of foreach
} // end of for
I have tested everything. Do you have any ideas how can I retransform this code without goto in order to be executed properly???
This questions demonstrates why goto should be avoided. It lets you get away without thinking about the algorithm enough.
The standard way to do this is with a flag. I hope you were not expecting a "herezthecode kthxbai" sort of an answer, but in this case the best way to explain it would be to write the code -
for($i=0;$i<30;$++){
$x=0;
do {
$found = false;
foreach($feed->get_items($x,1) as $item){
// get $id
if($id==$dbid){
$found = true;
break;
}else{
// other things
}
}
$x++;
} while($found);
}
Without knowing how the ->get_items() call behaves you could use this brute-force method in lieu of the goto-switch:
for($i = 0; $i < 30; $i++)
{
$x = 0;
$a = 1;
while ($a--)
foreach($feed->get_items($x, 1) as $item)
{
if($id == $dbid)
{
$x++;
$a=1; break;
}
else
{
}
} // end of foreach
} // end of for
The label gets replaced by a while and a self-fulfulling stop condition. And the goto becomes a break and resets the $a stop condition.
Something like this would probably work...
function loop(){
foreach($feed->get_items($x,1) as $item){
if($id==$dbid){
$x++;
loop();
}else{
}
}
}
for($i=0;$i<30;$++){
$x=0;
loop();
}
I'm sorry, I removed all the comments, they were annoying.
Move the declaration of $x outside of the for loop and replace your label/goto combination with a break, like so...
$x=0;
for($i=0;$i<30;$++) //print 30 articles
{
foreach($feed->get_items($x,1) as $item)
{
// create a unique id for the article of the feed
if($id==$dbid)
{
//if this id exists in the db,take the next article of the same feed which is not in the db
$x++;
continue;
}
else
{
//print the original article you grabbed
}
} // end of foreach
}//end of for
Agree with unset - using break will break if loop and keep iterating through for loop

cannot access the array using php

i have created an array using php something like this
$array1=array()
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
for($y=0;$y<$i;$y++)
{
print_r($array1[$y]);
}
}
it does not print the value.
If nothing else, you should move the inner loop out:
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
for($y=0;$y<5;$y++)
{
print_r($array1[$y]);
}
I just ran this code, the only change i made was putting a semicolon in the first line ;)
<?php
$array1=array();
for($i=0;$i<5;$i++)
{
$array1[$i]="abcd";
for($y=0;$y<$i;$y++)
{
print_r($array1[$y]);
}
}
?>
Output:
abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd
Based on #Jon's answer:
$array1 = array();
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
$count = count($array1);
for($y=0;$y<$count;$y++)
{
print_r($array1[$y]);
}
You can put the count function in the for loop, but that's bad practice. Also, if you are trying to get the value of EVERY value in the array, try a foreach instead.
$array1 = array();
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
foreach($array1 as $value)
{
print_r($value);
}
Because of the way how print_r works, it is silly to put it inside a loop, this will give you actual output and is error free :).
$array1=array();
for($i=0;$i<5;$i++)
{
$array1[$i]='somevalue';
}
print_r($array1);
for($y=0;$y<$i;$y++)
Your display loop isn't displaying the entry you've just added as $array[$i], because you're looping $y while it's less than $i
for($y=0;$y<=$i;$y++)

Categories