如何从PHP文件中包含数组并在另一个PHP文件中检查它

问题描述 投票:0回答:2

有问题让这个工作。我在'key.php'中有一个数组,我想将它包含在'processor.php'中并检查是否有一个已发布的值。我要么得到500个错误,要么将数组作为字符串返回。

key.php

<?php $foo = array('thing1', 'thing2'); ?>

processor.php

<?php
    $bar = include('/path/to/key.php');
    $email = $_POST('email');
    if (in_array($email, $bar)) {
       echo('in array');
    } else {
        echo('not in array');
    }
?>
php
2个回答
2
投票

尝试用if (in_array($email, $bar))更改if (in_array($email, $foo)),而不是像这样包含$bar = include('/path/to/key.php');这样的文件就像这个include '/path/to/key.php';一样。

要检查的变量名称为$ foo,而不是$ bar。包含其他php文件时,您不需要将它们设置为变量。让我知道事情的后续 :)


1
投票

Documentation说:

include语句包括并评估指定的文件。

这相当于将整个文件复制/粘贴到调用脚本中的该点。你应该这样做:

<?php
    include('/path/to/key.php'); //here you are defining $foo
    $bar = $foo; 
    //now you can continue with the rest of your original script
    $email = $_POST('email');
    if (in_array($email, $bar)) {
       echo('in array');
    } else {
        echo('not in array');
    }
?>

(或直接检查$ foo,而不是$ bar)

© www.soinside.com 2019 - 2024. All rights reserved.