foreach break delete array element

Discussion in 'PHP' started by lagna, Nov 9, 2012.

  1. #1
    I iterate through an array of objects and want to delete one of the objects based on it's 'id' property, but my code doesn't work.

    foreach($array as $element)
    {

    foreach($element as $key => $value)
    {

    if($key == 'id' && $value == 'searched_value')
    {

    //delete this particular object from the $array
    unset($element);//this doesn't work
    unset($array,$element);//neither does this
    }
    }
    }

    Suggest me !
     
    lagna, Nov 9, 2012 IP
  2. stephan2307

    stephan2307 Well-Known Member

    Messages:
    1,277
    Likes Received:
    33
    Best Answers:
    7
    Trophy Points:
    150
    #2
    try this.

    
    foreach($array as $key1=>$element) 
    {
    	foreach($element as $key => $value) 
    	{
    		if($key == 'id' && $value == 'searched_value')
    		{
    			//delete this particular object from the $array
    			unset($array[$key1]);
    		} 
    	}
    }
    
    PHP:
    and please use the [ PHP ] [/ PHP ] tags ( remove the spaces) when posting code so it's easier to read.
     
    stephan2307, Nov 9, 2012 IP
  3. dushmant

    dushmant Guest

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    foreach($array as $elementKey => $element) {
    foreach($element as $valueKey => $value) {
    if($valueKey == 'id' && $value == 'searched_value'){
    //delete this particular object from the $array
    unset($array[$elementKey]);
    }
    }
    }

    Lagna, I think this should be correct.
     
    dushmant, Nov 9, 2012 IP
  4. stephan2307

    stephan2307 Well-Known Member

    Messages:
    1,277
    Likes Received:
    33
    Best Answers:
    7
    Trophy Points:
    150
    #4
    @dushmant
    well done in rewriting my answer.
     
    stephan2307, Nov 9, 2012 IP