balanv
balanv

Reputation: 10898

How to delete values in two dimensional array (PHP)?

I have an array which looks like

        $cclArray[0]['url']='test.html';
        $cclArray[0]['entity_id']=9;
        $cclArray[1]['url']='test1.html';
        $cclArray[1]['entity_id']=10;
        $cclArray[2]['url']='test2.html';
        $cclArray[2]['entity_id']=11;

if i would like to remove a specific array, for example if i want to delete the array element with 'url'='test1.html' .. how do i do it?

Thanks a lot for helping.

Upvotes: 1

Views: 4313

Answers (6)

kapa
kapa

Reputation: 78691

If you are using PHP >5.3 you can do it simply like this:

$cclArray = array_filter($cclArray, function ($var) {
    return $var['url'] != 'test1.html';
});

Upvotes: 2

Dmitri
Dmitri

Reputation: 36290

for($i=0; $i<count($cclArray); $i++){
    if('test1.html' === $cclArray[$i]['url']){
        array_splice($cclArray, $i, 1);
    }
}

This is better but remember that unset() does not remove actual element it just sets it to null. If you want it to be complete gone, then after the unset() you should also do this: $cclArray = array_filter($cclArray);

Or you can do this in order to complete remove the array element instead of just unsetting it

for($i=0; $i<count($cclArray); $i++){
if('test1.html' === $cclArray[$i]['url']){
array_splice($cclArray, $i, 1);
}

}

Upvotes: 0

Headshota
Headshota

Reputation: 21449

foreach($cclArray as $key=>$val){
  if($val['url'] == 'test1.html'){
   unset($cclArray[$key]);
  }
}

I think this is it.

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157896

if you make your array this way

    $cclArray['test.html'] = 9;
    $cclArray['test1.html'] = 10;
    $cclArray['test2.html'] = 11;

it will be possible to delete with just

$url = 'test.html';
unset($cclArray[$url]);

Upvotes: 1

hsz
hsz

Reputation: 152216

foreach ( $cclArray as $k => $array ) {
    if ( $array['url'] == 'test1.html' ) {
        unset($cclArray[$k]);
    }
}

Upvotes: 2

heximal
heximal

Reputation: 10517

for ($i=0;$i<count($cclArray);$i++)
  if($cclArray[$i]['url']=='test.html') unset($cclArray[$i]['url'])

Upvotes: 0

Related Questions