The shortest way to echo out stuff in views in PHP - when not using template engines - is, afaik, this one:
<?php if (!empty($x)) echo $x; ?>
For a deeper explanaition why using !empty is a good choice please look here.
Is it possible to write this without writing the variable name twice (like in other languages), something like
!echo $x;
or
echo? $x;
echo #$x;
It's not exactly the right way to do it, but it is shorter.
it reduces the need to check if $x exists since # silences the error thrown when $x == null;
edit
echo empty($x) ? "" : $x;
is a shorter way, which is not really that much shorter nor does it solve your problem.
guess the other answers offer a better solution by addressing to make a short function for it.
Built in? No.
However - you could write your own wrapper function to do it:
$x = 'foobar';
myecho($x); // foobar
function myecho($x) {
echo !empty($x) ? $x : '';
}
This fits the bill of "only writing the variable once", but doesn't give you as much flexibility as the echo command does because this is a function that is using echo, so you can't do something like: myecho($x . ', '. $y) (the argument is now always defined and not empty once it hits myecho())
Easy approach would be to define an helper function so:
function mEcho($someVariable) {
if(!empty($someVariable) echo $someVariable;
}
I'm not sure though if that's what you intended.
Yes, you can write a function:
function echoIfNotEmpty($val) {
if (!empty($val)) {
echo $val;
}
}
Usage:
echoIfNotEmpty($x);
Sure you can shorten the function name.
If you don't know, if the var is intialized you can also do:
function echoIfNotEmpty(&$val = null) {
if (!empty($val)) {
echo $val;
}
}
Most times we want do prefix and append something
function echoIfNotEmpty(&$val = null, $prefix = '', $suffix = '') {
if (!empty($val)) {
echo $prefix . $val . $suffix;
}
}
echoIfNotEmpty($x, '<strong>', '</strong>');
Related
First time I am trying to use the dynamic create_function, and up to now, not much success :-)
My function is this :
function o99_brsa_custom_widgets() {
global $wp_meta_boxes;
global $o99_brsa_options;
for($i=0; $i> count($o99_brsa_options[content]); $i++) {
$widgt_id = 'o99_dashboard_widget_dyn' . $i;
$widgt_name = 'obmek99 widget name' . $i;
$out = $o99_brsa_options[content][$i];
$f = create_function(' $out ',' global $out; echo $out;');
do_the_widgets($widgt_id, $widgt_name, $f);
}
}
The do_the_widgets() action is accepting only a direct echo and prints the content of the widget.
The $o99_brsa_options[content] is a verified array with $i elements (each is content) .
The strange thing is that the $i is working on the $widgt_id and $widgt_name but on the create_function() I get the same value printed in all widgets . ( echo $out )
It seems that I do not know how to pass a simple variable to the new function ( I am using global inside create_function(), but it helps little as for now .
So, what is my mistake / misunderstanding / misuse now :-) ??
create_function was during the stone age , when kaᵠ used pen and paper to write applications, when PeeHaa埽 got a beer because he wrote hello would, The world is better now please use closures
$f = function ($out) {
echo $out;
};
$f("Welcome");
You would thank me one day, But you can only use create_function if you are Gordon (The machine from the past sent here to torment us) he wrote this
$fn = create_function(
'$x',
'return $x; } $foo = 42; function foo($int) { return $int; '
);
See Live Demo
How Can I get the string that present the variable in function argument?
example
function dbg($param){
return "param";
}
$var="Hello World";
echo dgb($var);
output: var
$arr=array();
echo dgb($arr);
output: arr
It is NOT possible to do what you ask reliably.
The closest you can come up to doing that is to do a debug_backtrace() to check which file called the function then tokenize the source of that file to find the reference.
Again, this will not work reliably. It will fail if you have multiple calls on one line. Truthfully, it isn't work the trouble. You are writing the code anyway, you know which variable you are passing.
function dbg($var) {
$bt = debug_backtrace();
$file = $bt[0]['file'];
$line = $bt[0]['line'];
$source = file_get_contents($file);
$tmpTokens = token_get_all($source);
$tokens = array ();
foreach ($tmpTokens as $token) {
if (is_array($token) && $token[0] !== T_INLINE_HTML && $token[0] !== T_WHITESPACE) {
$tokens[] = $token;
}
}
unset($tmpTokens);
$countTokens = count($tokens);
for ($i = 0; $i < $countTokens; $i++) {
if ($tokens[$i][3] > $line || $i === $countTokens - 1) {
$x = $i - (($tokens[$i][3] > $line) ? 1 : 0);
for ($x; $x >= 0; $x--) {
if ($tokens[$x][0] === T_STRING && $tokens[$x][1] === __FUNCTION__) {
if ($x !== $countTokens - 1 && $tokens[$x + 1][0] === T_VARIABLE) {
return $tokens[$x + 1][1];
}
}
}
}
}
return null;
}
printing a variable, you're doing it wrong.
the right ways is like this:
function dbg($param){
return $param;
}
$var="Hello World";
echo dgb($var);
and by the way you're passing an array to a function that only accepts variables. and oh it's a null array all the way worse!
I'm just guessing that you're trying to make a custom debugger which as a nice touch prints the name of the variable you're debugging. Well, that's not really possible. I'd suggest you look at debug_backtrace, which allows you to print the file, line number, function name and arguments of the place where you invoked your dbg function. Unless you use dbg more than once per line that helps you find the information you're looking for, and IMO is a lot more useful anyway.
Alternatively, you can have both the name and value of your variable if you call your function like this:
function dbg($var) {
echo 'name: ' . key($var) . ', value: ' . current($var);
}
$foo = 'bar';
dbg(compact('foo'));
You question doesnt make much sense, you may want to reword it.
It sounds like you want to use the $param in the function in which case you can just do something link echo $param;
I have things like this using eval():
$result = eval("return ".$value1.$operator.$value2.";");
Where the operator is from a variable, or a db field.
How would I go about achieving the same result without using eval? Is it possible?
It's not a security concern as the values/operator aren't user entered, but it may be a performance concern if this comment at the PHP manual is anything to go by. Plus, if at some point I want to try out Facebook's HipHop I need to replace all uses of eval with something else.
if(strcmp($operator, "+") == 0) {
return $value1 + $value2;
}
else if(strcmp($operator, "*") == 0) {
return $value1 * $value2;
}
...
As #Gumbo mentioned, you can also use switch()
Well, I'm not sure about operators, but you can do something like this with function names:
function add($x, $y) {
return $x + $y;
}
$value1 = 1;
$value2 = 2;
$func = "add";
$result = $func($value1, $value2);
You can even do this with builtin functions:
$func = 'array_sum';
$result = $func(array($value1, $value2));
I have the following PHP code which works out the possible combinations from a set of arrays:
function showCombinations($string, $traits, $i){
if($i >= count($traits)){
echo trim($string) . '<br>';
}else{
foreach($traits[$i] as $trait){
showCombinations("$string$trait", $traits, $i + 1);
}
}
}
$traits = array(
array('1','2'),
array('1','2','3'),
array('1','2','3')
);
showCombinations('', $traits, 0);
However, my problem is that I need to store the results in an array for processing later rather than just print them out but I can't see how this can be done without using a global variable.
Does anyone know of an alternative way to achieve something similar or modify this to give me results I can use?
Return them. Make showCombinations() return a list of items. In the first case you only return one item, in the other recursive case you return a list with all the returned lists merged. For example:
function showCombinations(...) {
$result = array();
if (...) {
$result[] = $item;
}
else {
foreach (...) {
$result = array_merge($result, showCombinations(...));
}
}
return $result;
}
In addition to the other answers, you could pass the address of an array around inside your function, but honestly this isn't nearly the best way to do it.
Using the variable scope modifier static could work. Alternatively, you could employ references, but that's just one more variable to pass. This works with "return syntax".
function showCombinations($string, $traits, $i){
static $finalTraits;
if (!is_array($finalTraits)) {
$finalTraits = array();
}
if($i >= count($traits)){
//echo trim($string) . '<br>';
$finalTraits[] = $string;
} else {
foreach($traits[$i] as $trait){
showCombinations("$string$trait", $traits, $i + 1);
}
}
return $finalTraits;
}
$traits = array(
array('1','2'),
array('1','2','3'),
array('1','2','3')
);
echo join("<br>\n",showCombinations('', $traits, 0));
Of course, this will work as expected exactly once, before the static nature of the variable catches up with you. Therefore, this is probably a better solution:
function showCombinations($string, $traits, $i){
$finalTraits = array();
if($i >= count($traits)){
$finalTraits[] = $string;
} else {
foreach($traits[$i] as $trait){
$finalTraits = array_merge(
$finalTraits,
showCombinations("$string$trait", $traits, $i + 1)
);
}
}
return $finalTraits;
}
although the solution by Lukáš is the purest as it has no side effects, it may be ineffective on large inputs, because it forces the engine to constantly generate new arrays. There are two more ways that seem to be less memory-consuming
have a results array passed by reference and replace the echo call with $result[]=
(preferred) wrap the whole story into a class and use $this->result when appropriate
the class approach is especially nice when used together with php iterators
public function pageslug_genrator($slug,$cat){
$page_check=$this->ci->cms_model->show_page($slug);
if($page_check[0]->page_parents != 0 ){
$page_checks=$this->ci->page_model->page_list($page_check[0]->page_parents);
$cat[]=$page_checks['re_page'][0]->page_slug;
$this->pageslug_genrator($page_checks['re_page'][0]->page_slug,$cat);
}
else
{
return $cat;
}
}
this function doesnt return any value but when i m doing print_r $cat it re
store the results in a $_SESSION variable.
function getTemplate($tpl if ($vars) echo ", $vars";)...function
Is this possible somehow?
The above wont work.
Thanks
Optional arguments with default values
It looks like you want an optional argument, which you can accomplish by defining a default value in the function definition:
function getTemplate($tpl, $vars=null)
{
}
You can call this function as getTemplate($foo) or getTemplate($foo,$bar). See the PHP manual page on function arguments for more details.
Variable numbers of arguments
It's also possible to write functions which take a variable number of arguments, but you need to use func_num_args, func_get_arg and func_get_args functions to get at them. Here's an example from the manual
<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
?>
Calling a function with a variable number of parameters
To round off this answer even more, suppose you'd build an array of 1..n values and wanted to pass it to the foo() function defined above? You'd use call_user_func_array
$values=(1,2,3,4);
call_user_func_array('foo', $values);
This is the equivalent of calling
foo(1,2,3,4);
What's so bad about
function getTemplate($tpl, $vars=null) {}
?
if ($vars) { getTemplate($tpl, $vars); }
else {{ getTemplate($tpl, null); }
(semi-pseudo code)
Or:
getTemplate($tpl, ($vars)?$vars:null); // not sure
getTemplate($tpl, (!empty($vars))?$vars:null);
Also, if you would like a technique similar to echo:
$code = "getTemplate($pl";
if ( $vars ) { $code = $code . ", $vars);"; }
else { $code = $code . ");"; }
$ret = eval($code);
Although this is usually considered bad practice (never say never).
Please note that all code sent to eval will be executed directly. So don't put user input in an eval() call.