Jump to content

Adding to an array from a nested loop


dragunu

Recommended Posts

Hello all,

Basically I have two arrays. The first array, $one, has 9 numbers ( 1 , 2 , 3 , 4 , 3 , 6 , 1 , 3 , 2 ) , { please not that there are numbers that are double } . Now, I'd like to have $two with just ( 1 , 2 ,3 ,4 , 6 ) , that is, $one but without the doubles. I have tried several solutions, and the closest i went is the following code, however, it is crashing my server. I can understand where its crashing it, but I somehow cant figure out the solution.


[code]
<?php

$one = array( 1 , 2 );
$two = array( "1" );



for ( $i=0 ; $i<count($one) ; $i++ )
  {
  $set = 0;
  for ( $c=0 ; $c<count($two) ; $c++ )
    {
    if ( trim($one[$i] ) !== trim($two[$c] ) )
      {
       
        $set = 1;
       
      }
      if ( $set == 1 )
        {
        $two[] = $one[$i];

     
    }
  }
 

?>

[/code]

thanks beforehand,
dragunu
Link to comment
https://forums.phpfreaks.com/topic/33575-adding-to-an-array-from-a-nested-loop/
Share on other sites

You've way over complicated things here.  Try this:

[code]<?php
// Assign values to array
$one = array(1,2,3,4,3,6,1,3,2);

// Create an array of unique values from $one
$two = array_unique($one);

// Output as proof
echo "<pre>\n";
print_r($two);
echo "</pre>\n";
?>[/code]

Regards
Huggie

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.