Removing Elements from an Array

Discussion in 'PHP' started by XT Gohan, Aug 28, 2008.

  1. #1
    I've scanned a directory and now I've removed elements from an array that I didn't want to be there via a conditional. Now the problem I have is when I run the script via a for-loop to display the array (the elements I removed would display as blanks).

    So the problem is that say I removed an array at the second position like $array[2] - It will display as a blank. How do I get around that?

     
    XT Gohan, Aug 28, 2008 IP
  2. rohan_shenoy

    rohan_shenoy Active Member

    Messages:
    441
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    60
    #2
    How are you removing the values?
    
    $array[2]='';
    //or
    unset($array[2]);//use this
    
    PHP:
     
    rohan_shenoy, Aug 28, 2008 IP
  3. XT Gohan

    XT Gohan Greenhorn

    Messages:
    29
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #3
    
    	foreach($array as $key => $value) {
    	  if($value == ".." || $value == "." || $value == "error_log") {
    		unset($array[$key]);
    	  }
    	}
    
    PHP:
    Now when I use the for loop to display the array, it displays blanks for those values because when I remove the array, it actually removes that element number together. To avoid this I used array_values() function but it still leaves one blank.

    Edit: Here's the for-loop I'm using:
    		$size = sizeof($array);
    	for ($i = 0; $i <= $size; $i++) {
    	   echo $array[$i];
    	}
    PHP:
     
    XT Gohan, Aug 28, 2008 IP
  4. CreativeClans

    CreativeClans Peon

    Messages:
    128
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Don't use the for-loop to loop through the array. Use a foreach-loop.
     
    CreativeClans, Aug 29, 2008 IP