开发者

deleting last array value ? php

1 question type

$transport = array('foot', 'bike', 'car', 'plane');

can i delete the plane ? is there a way ?

2 question type

 $transport = array('',开发者_Go百科 'bike', 'car', ''); // delate the last line
 $transport = array('', 'bike', 'car', 'ferrari'); // dont the last line
 $transport = array('ship', 'bike', 'car', 'ferrari'); // dont the last line

is there a easy way to delete the last array " if last array value is empty then delete " if not empty then don't delete ? but not to delete the first array ?


if(empty($transport[count($transport)-1])) {
    unset($transport[count($transport)-1]);
}


The easiest way: array_pop() which will pop an element of the end of the array.

As for the 2nd question:

if (end($transport) == "") { 
    array_pop($transport); 
}

Should handle the second.

EDIT:

Modified the code to conform to the updated information. This should work with associative or indexed based arrays.

Fixed the array_pop, given Scott's comment. Thanks for catching that!

Fixed the fatal error, I guess empty cannot be used with end like I had it. The above code will no longer catch null / false if that is needed you can assign a variable from the end function and test that like so:

$end_item = end($transport);
if (empty($end_item)) { 
    array_pop($transport); 
}

Sorry for posting incorrect code. The above I tested.


for # 1,

$transport=array_slice($transport,0,count($transport)-1)


You can simply do that by array_pop() function:

array_pop($transport);


$endvalue = & end($transport);
array_pop($endvalue);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜