Steve
Steve

Reputation: 4898

Preventing "undefined" errors from displaying in PHP

I have PHP code that tries to read a lot of values that may or may not be there. Each of these failed reads displays an "undefined" error. I can silence it with something like

if(!empty($meta['image_1_url'])) $image_1_url = $meta['image_1_url']; 

but I'd rather PHP just not complain about them. I've commented out the

<?php

    //ini_set('display_errors', 1);
    //error_reporting(E_ALL);

I had at the top of my page but the errors still print out.

Does anyone know how I can keep there errors from printing?

Upvotes: 1

Views: 56

Answers (2)

devpro
devpro

Reputation: 16117

If you are getting notice on the mentioned example in question than it means you are using an index or vairable without defining it any where in your code. Your example:

if(!empty($meta['image_1_url'])) $image_1_url = $meta['image_1_url']; 

This can be check by using isset(). Either value set or not and define empty value in variable if value not set.

if(isset($meta['image_1_url']) && !empty( $meta['image_1_url'] )){

     $image_1_url = $meta['image_1_url']; 
}
else{
    $image_1_url = '';
}

For the other issue preventing undefined notice, note that it's good practice to on error_reporting in development line it's save your time.

If you are getting notices than keep in mind your code will not work. It can only work if you get warnings. Your code will execute if you ignore the warnings.

Upvotes: 0

Mathew Tinsley
Mathew Tinsley

Reputation: 6976

 error_reporting(E_ALL & ~E_NOTICE);

The above will display errors and warnings, but not notices.

https://secure.php.net/manual/en/function.error-reporting.php

Keep in mind that notices can be useful. In general it is better to write your code in such a way that notices shouldn't be generated unless there is a problem.

In addition to the example you provided, you can also use the ternary operator:

$image_1_url = isset($meta['image_1_url']) ? $meta['image_1_url'] : '';

The above code won't generate a notice, even if image_1_url is not set.

As of PHP 7, you can also use the Null Coalesce Operator

$image_1_url = $meta['image_1_url'] ?? '';

Upvotes: 7

Related Questions