简体   繁体   中英

Handling assignment to undefined index and E_NOTICE

Looks like a lot of people did not understand the question, the notice I am getting is not about $fromdatabase, it's about $data[$key]

For I can see in the development environment what I am getting as $fromDatabase[$key], and the error message is for the line : $data [$key] = $this->getSomeValue ($value);

Even if I do $data ['mykey'] I get the message undefined index mykey

I have a situation where I need to assign some value to an undefined index of an associative array. Something like this:

$data = array (  );

foreach ( $something as $key => $value)
{
    /** If I do this then there is no notice **/
    $data['body'][$key] = NULL;

    foreach ( $fromDatabase as $xyz)
    {
        $data['body'][$key] = $this->getSomeValue ($xyz);
    }
}

$fromDatabase is not known and $key can not be predicted beforehand, all of them are dynamic.

How do I handle the E_NOTICE (undefined index) in this situation?

E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

PHP Manual says that but why am I getting the error while appending elements to the uninitialized array ?

You just need to make sure $fromDatabase exists and is an array, the rest will be OK.

$data[$key] will be created if it doesn't exist and $key and $value will be set automatically.

$data = array (  );

if (isset($fromDatabase) && is_array($fromDatabase))
    foreach ( $fromDatabase as $key => $value )
    {
        $data[$key] = $this->getSomeValue ($value); // You made a typo "key" => "$key"
    }

EDIT : I can't reproduce your error

$fromDatabase = ['test' => 1, 42 => 'some strange value'];

$data = array (  );
foreach ( $fromDatabase as $key => $value )
{
    $data[$key] = $value;
}

print_r($data);

Outputs (for me) :

Array
(
    [test] => 1
    [42] => some strange value
)

RE-EDIT :

$data = array (  );

change it to

$data = array('body' => array());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM