Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove specific keys from Array? PHP

Tags:

arrays

php

key

I am trying to remove keys from array.

Here is what i get from printing print_r($cats);

Array
(
    [0] => <a href="/website/index.php/Category:All" title="Category:All">All</a> &gt; <a href="/website/index.php/Category:Computer_errors" title="Category:Computer errors">Computer errors</a> &gt; <a href="/website/index.php/Category:HTTP_status_codes" title="Category:HTTP status codes">HTTP status codes</a> &gt; <a href="/website/index.php/Category:Internet_terminology" title="Category:Internet terminology">Internet terminology</a> 
    [1] => 
<a href="/website/index.php/Category:Main" title="Category:Main">Main</a> 
)

I am trying to use this to remove "Main" category from the array

    function array_cleanup( $array, $todelete )
{
    foreach( $array as $key )
    {
        if ( in_array( $key[ 'Main' ], $todelete ) )
        unset( $array[ $key ] );

    }
    return $array;
}

$newarray = array_cleanup( $cats, array('Main') );

Just FYI I am new to PHP... obviously i see that i made mistakes, but i already tried out many things and they just don't seem to work

like image 943
user585303 Avatar asked Mar 05 '11 06:03

user585303


1 Answers

Main is not the element of array, its a part of a element of array

function array_cleanup( $array, $todelete )
{
    $cloneArray = $array;
    foreach( $cloneArray as $key => $value )
    {
        if (strpos($value, $todelete ) !== false)   
           unset( $array[ $key ] );     //$array[$key] = str_replace($toDelete, $replaceWith, $value) ;  // add one more argument $replaceWith to function 

    }
    return $array;
}

Edit:

with array

function array_cleanup( $array, $todelete )
    {
      foreach($todelete as $del){
        $cloneArray = $array;
        foreach( $cloneArray as $key => $value )
        {          
            if (strpos($value, $del ) !== false)   
               unset( $array[ $key ] );     //$array[$key] = str_replace($toDelete, $replaceWith, $value) ;  // add one more argument $replaceWith to function 

           }
    }
     return $array;
}

  $newarray = array_cleanup( $cats, array('Category:Main') );
like image 128
Gaurav Avatar answered Oct 10 '22 17:10

Gaurav