Catch undefined index in array and create it - php

<h1><?php echo $GLOBALS['translate']['About'] ?></h1>
Notice: Undefined index: About in page.html on line 19
Is it possible to "catch" an undefined index so that I can create it (database lookup) & return it from my function and then perform echo ?

The easiest way to check if a value has been assigned is to use the isset method:
if(!isset($GLOBALS['translate']['About'])) {
$GLOBALS['translate']['About'] = "Assigned";
}
echo $GLOBALS['translate']['About'];

You can check if this particular index exists before you access it. See the manual on isset(). It's a bit clumsy as you have to write the variable name twice.
if( isset($GLOBALS['translate']['About']) )
echo $GLOBALS['translate']['About'];
You might also consider changing the error_reporting value for your production environment.

that wouldn't be the right thing to do. i would put effort into building the array properly. otherwise you can end up with 1000 db requests per page.
also, you should check the array before output, and maybe put a default value there:
<h1><?php echo isset($GLOBALS['translate']['About'])?$GLOBALS['translate']['About']:'default'; ?></h1>

try something like:
if ( !isset($GLOBALS['translate']['About']) )
{
$GLOBALS['translate']['About'] = get_the_data('About');
}
echo $GLOBALS['translate']['About'];

Yes. Use isset to determine if the index is defined and then, if it isn't, you can assign it a value.
if(!isset($GLOBALS['translate']['About'])) {
$GLOBALS['translate']['About'] = 'foo';
}
echo "<h1>" . $GLOBALS['translate']['About'] . "</h1>";

You need to define your custom error handler if you want to catch Undefined index
set_error_handler('exceptions_error_handler');
function exceptions_error_handler($severity, $message, $filename, $lineno) {
if (error_reporting() == 0) {
return;
}
if (error_reporting() & $severity) {
throw new ErrorException($message, 0, $severity, $filename, $lineno);
}
}
try{
}catch(Exception $e){
echo "message error";
}

Related

making dynamic defined constants php

look at this syntax of variable name modifying:
${'a' . 'b'} = 'hello there';
echo $ab;
this returns "hello there"
But i want do declare defined variables dynamical.
$error_code = $_GET[error_code]; //for example: 404
define(E404, 'Not found');
echo E{$error_code};
It return error, i want to generate E404 dynamical on php codes and get its value.
I have no idea what the syntax or the technique I'm looking for is here, which makes it hard to research.
You need to call constant() to retrieve the value of a constant from a string. Your example should look like:
$error_code = 404;
define('E404', 'Not found');
echo constant("E{$error_code}");
and it will display Not found.
<?php
$ErrorCode = $_GET['error_code']; // Where error_code = 404
$Errors = array(); // here we are creating a new array.
$Errors[$ErrorCode] = "Whatever"; // here we are setting a key of the new array, with the keys name being equal to the $ErrorCode Variable
print_r($Errors); // Would return Array( [404] => Whatever);
echo $Errors["404"]; // Would return Whatever
?>
Well Php has a feature called variable variables. See this link: http://php.net/manual/en/language.variables.variable.php. It allows a variable name to be assigned to a variable.

How can I check if my function print/echo's something?

I am often using echo to debug function code:
public function MyFunc() {
// some code...
echo "OK";
// some code...
}
How can I check that my function print's/echo's something?
(pseudo code):
MyFunc();
if (<when something was printed>){
echo "You forgot to delete echo calls in this function";
}
This should work for you:
Just call your functions, while you have output buffering on and check if the content then is empty, e.g.
ob_start();
//function calls here
MyFunc();
$content = ob_get_contents();
ob_end_clean();
if(!empty($content))
echo "You forgot to delete echos for this function";
You could create a $debug flag and a debuglog() function, which checks for the debug flag and only then echos the message. Then you can toggle your debug messages on and off from one location.
define('DEBUGMODE', true); // somewhere high up in a config
function debuglog($msg){
if( DEBUGMODE ){ echo $msg; }
}
Should you ever want to get rid of your debug echos, you can search for "debuglog(" and delete those lines of code. This way you won't accidentally delete any echo statements that are required in normal execution or miss any debug echo statements that should really have been removed.
It's the bad way checking if something is echoed.
You can set a variable named is_echoed to 1 or you can return the value
public $is_echoed = 0;
//rest
$this->is_echoed = 1;
or
function myFunc()
{
return "OK";
}
if(myFunc() == 'OK')
//rest
You can use var_dump() and die() to debug your code more efficiently.
$test = "debud test";
public function MyFunc($test)
{
// some code...
var_dump($test); die();
// some code...
}
Reference:
http://php.net/manual/en/function.var-dump.php
http://php.net/manual/en/function.die.php
Why do you want to try such an extensive process of seeing if something has been echoed or not?
For debugging you can definitely use echo to see if the particular block is being hit during a particular use-case. But I would suggest you use flags and return the values to the calling function.
function xyz () {
if (something) return some_value;
else return some_other_value;
}
There is no particular need to have variables and use space in storing a 0 or 1 when you can just return a hard-coded literal.
I would suggest to you to use something like log4php [1]
But if not, I use a function like this:
define('DEBUG', true);
function debug($msg){
if(DEBUG){ echo $msg; }
}
Or something like this to see the log in the browser console:
function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}

Why does this PHP code give "undefined index"?

I have this code:
print_r(array_keys($variables));
if (array_key_exists('form', $variables)) {
print "YES!";
}
$imgs = $variables['form']['field_images'];
It's a part of the code that I use to theme a form page in Drupal. YES is printed out, however, drupal reports undefined index for that. Thanks for your generous help
$variables['form'] does exist, but $variables['form']['field_images] probably not. That's why you get the notice about undefined index.
So you should make sure that the subkey also exists before you are calling it.
as an example implemenation of Ikke`s answer:
if ( !array_key_exists('form', $variables) ) {
echo 'missing parameter form';
}
else if ( !array_key_exists('field_images', $variables['form']) ) {
echo 'missing parameter field_images';
}
else {
$imgs = $variables['form']['field_images'];
}
Try this:-
PHP throws the notice. You can add an isset() or !empty() check to avoid the error, like such:
if(isset($variables)) ) && !empty($variables)) ))
{
if (array_key_exists('form', $variables)) {
print "YES!";
}
$imgs = $variables['form']['field_images'];
}

Elseif include, and echo an outside variable?

I have an Elseif statement, which gets a template name and includes the template PHP file which contains a large array, it outputs the result on the page.
$template = str_replace("-","_","{$_GET['select']}");
if ($template == "cuatro"){
include("templates/cuatro.php");
echo $page_output;
} elseif ($template == "ohlittl"){
include("templates/ohlittl.php");
echo $page_output;
} else {
echo "Sorry, template not found.";
}
$page_output = "You've chosen $template_select[0].";
From there, I get a notice saying it couldn't find the $page_output variable.
Notice: Undefined variable: page_output in C:\ ... \template.php on line 10
It can find it if I put the variable in the included file though. But I'm trying to get this variable to remain on this page. How do I complete this?
You are defining $page_output after you are echoing it. At the time you call echo $page_output it doesn't exist yet.
Try:
$page_output = "You've chosen {$template_select[0]}.";
$template = str_replace("-","_","{$_GET['select']}");
if ($template == "cuatro"){
include("templates/cuatro.php");
echo $page_output;
} elseif ($template == "ohlittl"){
include(dirname(__FILE__) . "/templates/ohlittl.php");
echo $page_output;
} else {
echo "Sorry, template not found.";
}
Although I have no idea how you are setting $template_select and if you are aware it will always say the same template name?
An alternative approach that I believe achieves what you want:
$templates = array('cuatro', 'ohlittl');
$selectedTemplate = strtolower(str_replace("-","_",$_GET['select']));
foreach ($templates as $template)
{
if ($template === $selectedTemplate) {
include(dirname(__FILE__) . "/templates/" . $template . ".php");
echo "You've chosen {$template}.";
}
}
Either your template
Outputs the text directly (echo)
Stores the result in a global (e.g. $page_output) or a local variable (in the include happens inside a function, but that's transparent for the template).
Returns the output (yes, includes can return values).
You seem to want option 2, yet your templates are not defining any $page_output variable. You could also output the text directly in the templates, buffer the output, and assign it to $page_output:
ob_start();
include "file.php.inc";
$page_output = ob_get_contents();
ob_end_clean();

Handle error when getimagesize can't find a file

when I'm trying to getimagesize($img) and the image doesn't exist, I get an error. I don't want to first check whether the file exists, just handle the error.
I'm not sure how try catch works, but I want to do something like:
try: getimagesize($img) $works = true
catch: $works = flase
Like you said, if used on a non-existing file, getimagesize generates a warning :
This code :
if ($data = getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
will get you a
Warning: getimagesize(not-existing.png) [function.getimagesize]:
failed to open stream: No such file or directory
A solution would be to use the # operator, to mask that error :
if ($data = #getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
As the file doesn't exist, $data will still be false ; but no warning will be displayed.
Another solution would be to check if the file exists, before using getimagesize ; something like this would do :
if (file_exists('not-existing.png') &&
($data = getimagesize('not-existing.png'))
) {
echo "OK";
} else {
echo "NOT OK";
}
If the file doesn't exist, getimagesize is not called -- which means no warning
Still, this solution is not the one you should use for images that are on another server, and accessed via HTTP (if you are in this case), as it'll mean two requests to the remote server.
For local images, that would be quite OK, I suppose ; only problem I see is the notice generated when there is a read error not being masked.
Finally :
I would allow errors to be displayed on your developpement server,
And would not display those on your production server -- see display_errors, about that ;-)
Call me a dirty hacker zombie who will be going to hell, but I usually get around this problem by catching the warning output into an output buffer, and then checking the buffer. Try this:
ob_start();
$data = getimagesize('not-existing.png');
$resize_warning = ob_get_clean();
if(!empty($resize_warning)) {
print "NOT OK";
# We could even print out the warning here, just as PHP would do
print "$resize_warning";
} else {
print "OK"
}
Like I said, not the way to get a cozy place in programmer's heaven, but when it comes to dysfunctional error handling, a man has to do what a man has to do.
I'm sorry that raise such old topic. Recently encountered a similar problem and found this topic instead a solution. For religious reasons I think that '#' is bad decision. And then I found another solution, it looks something like this:
function exception_error_handler( $errno, $errstr, $errfile, $errline ) {
throw new Exception($errstr);
}
set_error_handler("exception_error_handler");
try {
$imageinfo = getimagesize($image_url);
} catch (Exception $e) {
$imageinfo = false;
}
This solution has worked for me.
try {
if (url_exists ($photoUrl) && is_array (getimagesize ($photoUrl)))
{
return $photoUrl;
}
} catch (\Exception $e) { return ''; }
Simple and working solution based on other answers:
$img_url = "not-existing.jpg";
if ( is_file($img_url) && is_array($img_size = getimagesize($img_url)) ) {
print_r($img_size);
echo "OK";
} else {
echo "NOT OK";
}

Categories