Access variable in function from another function. php - php

I have this function
function theme_status_time_link($status, $is_link = true) {
$time = strtotime($status->created_at);
if ($time > 0) {
if (twitter_date('dmy') == twitter_date('dmy', $time) && !setting_fetch('timestamp')) {
$out = format_interval(time() - $time, 1). ' ago';
} else {
$out = twitter_date('H:i', $time);
}
} else {
$out = $status->created_at;
}
if ($is_link)
$out = "<a href='status/{$status->id}' class='time'>$out</a>";
return $out;
}
and this
function twitter_is_reply($status) {
$html = " <b><a href='user/{$status->from->screen_name}'>{$status->from->screen_name}</a></b><br /> $actions $link<br />{$text} <small>$source</small>";
}
I need to pass the variable $out from the first function to the second function, precisely to the $html variable in the second function. However, everything I try either gives me errors and outputs nothing. Without using globals because it appears multiple times in my script. Thanks.

If you want to use functions send it as an argument:
function twitter_is_reply($status, $html) {
$html .= " <b><a href='user/{$status->from->screen_name}'>{$status->from->screen_name}</a></b><br /> $actions $link<br />{$text} <small>$source</small>";
return $html;
}
Usage:
$out = theme_status_time_link();
echo twitter_is_reply('helloworld', $out);

Now you start to understand why OO is so good.
Create one class, make the $out a member of it and the two functions, make them methods of that class.

Related

How to return multiple times from a function?

I am trying to return values in php for sql injection, but the return is stopping my function. Here is the example:
function ex($input) {
if (strlen($input) > 5)
{
return $input;
}
return ":the end";
}
echo ex("helloa");
When I use return inside the function it ends it and ex("helloa") == "helloa" not "helloa:the end" like I want it to.
Concatenating Strings in a Function
When you want to have multiple strings, and actually wanna concatenate (or join) them. You can keep on adding them together in a variable and then, return that variable at the end of the function.
function ex($input) {
$return = "";
if (strlen($input) > 5)
{
$return .= $input;
}
$return .= ":the end";
return $return;
}
echo ex("helloa");
Using an array to pseudo-return multiple values
If you really want to return multiple values/strings, you can instead tell the function to return an array. You can only return one output though from a function.
function ex($input) {
// this array acts as a container/stack where you can push
// values you actually wanted to return
$return = array();
if (strlen($input) > 5)
{
$return[] = $input;
}
$return[] = ":the end";
return $return;
}
// you can use `implode` to join the strings in this array, now.
echo implode("", ex("helloa"));
Use
function ex($input) {
return (strlen($input) > 5 ? $input : '') . ":the end";
}

Return in recursive function php

I've got a little problem with recursive function output. Here's the code:
function getTemplate($id) {
global $templates;
$arr = $templates[$id-1];
if($arr['parentId'] != 0) {
$arr['text'] .= str_replace($arr['attr'], $arr['text'], getTemplate($arr['parentId']));
}
return $arr['text'];
}
The problem is that that function returns a value on each iteration like this:
file.exe
category / file.exe
root / category / file.exe
And I need only the last string which resembles full path. Any suggestions?
//UPD: done, the problem was with the dot in $arr['text'] .= str_replace
Try this please. I know its using global variable but I think this should work
$arrGlobal = array();
function getTemplate($id) {
global $templates;
global $arrGlobal;
$arr = $templates[$id-1];
if($arr['parentId'] != 0) {
array_push($arrGlobal, getTemplate($arr['parentId']));
}
return $arr['text'];
}
$arrGlobal = array_reverse($arrGlobal);
echo implode('/',$arrGlobal);
Try this,
function getTemplate($id) {
global $templates;
$arr = $templates[$id-1];
if($arr['parentId'] != 0) {
return $arr['text'] .= str_replace($arr['attr'], $arr['text'], getTemplate($arr['parentId']));
}
}
Give this a try:
function getTemplate($id, array $templates = array())
{
$index = $id - 1;
if (isset($templates[$index])) {
$template = $templates[$index];
if (isset($template['parentId']) && $template['parentId'] != 0) {
$parent = getTemplate($template['parentId'], $templates);
$template['text'] .= str_replace($template['attr'], $template['text'], $parent);
}
return $template['text'];
}
return '';
}
$test = getTemplate(123, $templates);
echo $test;

php foreach loop use variable in function name

I have a foreach loop that creates a function for each array item. I need a unique name for each function created and would like to include the current array item in the function name but don't know how to do this.
At the moment I have the function named as "function ttm_global__shortcode()" however I would like it to be "function ttm_global_$acf_field_shortcode()"
$acf_fields = array("telephone_number", "fax_number", "email_address", "skype");
foreach($acf_fields as $acf_field) {
function ttm_global__shortcode() {
ob_start();
echo get_field($acf_field, 'options');
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_shortcode($acf_field, 'ttm_global_'.$acf_field.'_shortcode');
}
Thanks
Using PHP 5.3 this can be done with anonymous functions
foreach($acf_fields as $acf_field) {
add_shortcode($acf_field, function() use($acl_field) {
// ...
});
}
If the second parameter of add_shortcode is a call back I think you can do it without creating such function.
$output = get_field($acf_field, 'options');
add_shortcode($acf_field, create_function('',"return '$output';"));
If you still want to create function.
Before PHP 5.3.0
Use create_function
foreach($acf_fields as $acf_field)
{
$funcs[$acf_field] = create_function('$acf_field', '
ob_start();
echo get_field($acf_field, 'options');
$output = ob_get_contents();
ob_end_clean();
return $output;'
);
....
}
After PHP 5.3.0
foreach($acf_fields as $acf_field)
{
$funcs[$acf_field] = function($acf_field){
ob_start();
echo get_field($acf_field, 'options');
$output = ob_get_contents();
ob_end_clean();
return $output;
};
....
}
Note: A parameter is added to your function.
You can use the create_function method to creates an anonymous function from the parameters passed, and returns a unique name for it.
<?php
function process($var1, $var2, $farr)
{
foreach ($farr as $f) {
echo $f($var1, $var2) . "\n";
}
}
// create a bunch of math functions
$f1 = 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}';
$f2 = "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);";
$f3 = 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }';
$farr = array(
create_function('$x,$y', 'return "some trig: ".(sin($x) + $x*cos($y));'),
create_function('$x,$y', 'return "a hypotenuse: ".sqrt($x*$x + $y*$y);'),
create_function('$a,$b', $f1),
create_function('$a,$b', $f2),
create_function('$a,$b', $f3)
);
echo "\nUsing the first array of anonymous functions\n";
echo "parameters: 2.3445, M_PI\n";
process(2.3445, M_PI, $farr);
// now make a bunch of string processing functions
$garr = array(
create_function('$b,$a', 'if (strncmp($a, $b, 3) == 0) return "** \"$a\" '.
'and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";'),
create_function('$a,$b', '; return "CRCs: " . crc32($a) . ", ".crc32($b);'),
create_function('$a,$b', '; return "similar(a,b) = " . similar_text($a, $b, &$p) . "($p%)";')
);
echo "\nUsing the second array of anonymous functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
?>
check out http://us.php.net/manual/en/function.create-function.php for more details.

print an array as code

I want to convert a big yaml file to PHP array source code. I can read in the yaml code and get back a PHP array, but with var_dump($array) I get pseudo code as output. I would like to print the array as valid php code, so I can copy paste it in my project and ditch the yaml.
You're looking for var_export.
You could use var_export, serialize (with unserialize on the reserving end), or even json_encode (and use json_decode on the receiving end). The last one has the advantage of producing output that can be processed by anything that can handle JSON.
Don't know why but I could not find satisfying code anywhere.
Quickly wrote this. Let me know if you find any errors.
function printCode($array, $path=false, $top=true) {
$data = "";
$delimiter = "~~|~~";
$p = null;
if(is_array($array)){
foreach($array as $key => $a){
if(!is_array($a) || empty($a)){
if(is_array($a)){
$data .= $path."['{$key}'] = array();".$delimiter;
} else {
$data .= $path."['{$key}'] = \"".htmlentities(addslashes($a))."\";".$delimiter;
}
} else {
$data .= printCode($a, $path."['{$key}']", false);
}
}
}
if($top){
$return = "";
foreach(explode($delimiter, $data) as $value){
if(!empty($value)){
$return .= '$array'.$value."<br>";
}
};
return $return;
}
return $data;
}
//REQUEST
$x = array('key'=>'value', 'key2'=>array('key3'=>'value2', 'key4'=>'value3', 'key5'=>array()));
echo printCode($x);
//OUTPUT
$array['key'] = 'value';
$array['key2']['key3'] = 'value2';
$array['key2']['key4'] = 'value3';
$array['key2']['key5'] = array();
Hope this helps someone.
An other way to display array as code with indentation.
Tested only with an array who contain string, integer and array.
function bo_print_nice_array($array){
echo '$array=';
bo_print_nice_array_content($array, 1);
echo ';';
}
function bo_print_nice_array_content($array, $deep=1){
$indent = '';
$indent_close = '';
echo "[";
for($i=0; $i<$deep; $i++){
$indent.=' ';
}
for($i=1; $i<$deep; $i++){
$indent_close.=' ';
}
foreach($array as $key=>$value){
echo "<br>".$indent;
echo '"'.$key.'" => ';
if(is_string($value)){
echo '"'.$value.'"';
}elseif(is_array($value)){
bo_print_nice_array_content($value, ($deep+1));
}else{
echo $value;
}
echo ',';
}
echo '<br>'.$indent_close.']';
}

How do I store the results of this recursive function?

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.

Categories