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.
Related
With my function what I have written I try thereby 2 things.
The links should be called like this http://localhost/?login=Bla, Now it is like this http://localhost/login,php?login "Bla
Next I would have asked, in my function a 1 is given after each call. I just can't figure out where this comes from, I've been sitting on this problem for a long time.
Output with the 1
This is the code with which I can call the pages
function Seite($pagename, $lay){
function Seite($pagename, $lay){
$path = "$lay/$pagename.php";
if (file_exists($path)) {
openSeite($path);
}
}
function openSeite($pageurl){
$fc = require($pageurl);
echo $fc;
}
function echopage($slug, $fade){
// $slug = ?SLUG=Seite
// $fade = Ordner des Layout
$page = isset($_GET["$slug"]) ? $_GET["$slug"] : "error";
$contente = seite($page, "$fade");
echo $contente;
}
I call the content on the index.php with
<? echopage("login", "admin/layout"); ?>
isset($_GET["$slug"]) returns a 1 because it is set (true), write a traditional conditional with the echo inside the if statement.
*Better Yet assign your output to a variable and concatenate the values accordingly.
$output = NULL;
if(isset($_GET["$slug"]){
$contente = seite($page, "$fade");
$output .= $contente;
}else{
//handle error
}
HTML:
<?=$output?><!--Output your displayed text held in the variable-->
ISSUE:
$page = isset($_GET["$slug"]) ? $_GET["$slug"] : "error";
You are essentially returning the set value, which is 1 also true.
From php manual for value: Returns TRUE if var exists and has any value other than NULL. FALSE otherwise.
You can test this by simply writing out a line of code echo isset($var); and checking the test php page. Then try defining a variable and doing the same thing. $var = "this is set"; then echo isset($var);, you will get a 1.
I was using variables in my php file without declaring them. It was working perfect in old version of localhost (i.e vertrigoServ 2.22).
But when I moved to latest version of localhost (i.e xampp 3.2.1), I encountered variables declaration warnings and errors something like this:
Notice: Undefined variable: att_troops_qty in D:\Installed
Programs\htdocs\dashboard\WarLord\PHP_Code\MyAjax.php on line 1247
So I declared all the variables at the top of php file like this:
$page = "";
$att_troops_qty = "";
$def_troops_qty = "";
$ca_level = "";
$b_level = "";
$pre_buildings = "";
$created_pre_b = "";
$building_id = "";
$building_loc = "";
$ca_1_b_loc = "";
$ca_1_b_level = "";
$ca_2_b_loc = "";
$ca_2_b_level = "";
It solved the problem But I have confusion that this is not the proper way to declare variables.
Is there some more better way for variables declaration?
How you are declaring is perfectly alright and proper way.
$test = "";
or
$test = null;
these both are proper ways for declaring empty variables.
for more info please visit http://php.net/manual/en/language.types.null.php
You need to declare variables before echoing them out. An example is here:
<?php
$var = "test";
echo $var; // it will echo out test
?>
And trying to echo out a variable this way will generate an error:
<?php
echo $var; // it will generate error
$var = "test";
?>
In addition, you can declare variables in another file and can include that file to echo out the variable somewhere. Remember to include the file first and then call it.
Example vars.php:
<?php
// define vars
$var1 = "Test 1";
$var2 = "Test 2";
?>
Now in another file, include vars.php first and then call the variable:
<?php
require_once"vars.php";
echo $var1;
?>
You cannot use undeclared variables but
you can declare them on the go.
Inside functions you can do something like that:
function abc() {
return $newVar or null; // without variable declaration
}
If $newVar is not declared before function will return null;
Or better way:
function abc($newVar = null) {
return $newVar; // with variable declaration
}
The best way to check whether the variable is declare or not, is to use the isset() function, which checks whether the variable is set or not like:
<?php
if(isset($a)){
// execute when $a is set ( already declare ) or have some value
}
else {
// execute when $a not set
}
?>
You can declare variables in php as
<?php
$test = "xyz" //for String datatype
$test1 = 10 //for integer datatype
?>
Name of a variable declared must be alphanumeric and you don't need to specify the type.
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'];
}
<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";
}
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();