如何在数组中插入if函数

时间:2015-12-26 18:23:50

标签: php arrays if-statement

我有一个数组

$ data_array =

array
    (
        "limit" => $limit,
        "page_number" => $page,
        "books" => $books
    );

我希望如果设置了$ books,那么数组应该是

array
    (
        "limit" => $limit,
        "page_number" => $page,
        "books" => $books
    );

如果未设置变量$ books,则数组应为

array
(
    "limit" => $limit,
    "page_number" => $page
);

请有人帮助我。

3 个答案:

答案 0 :(得分:1)

if(isset($books))
{
    $data_array=array
    (
        "limit" => $limit,
        "page_number" => $page,
        "books" => $books
    );
}
else
{
    $data_array=array
    (
        "limit" => $limit,
        "page_number" => $page
    );
}

答案 1 :(得分:1)

        array
        (
            "limit" => $limit,
            "page_number" => $page,
        );
        if ($books is set) 
           array['books'] = $books;

我认为这应该可以胜任。

答案 2 :(得分:1)

最好的方法是使用

$data_array = array
(
    "limit" => $limit,
    "page_number" => $page
);

if(isset($books)){
    $data_array['books'] = $books;
}