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.
Related
I am using a recursive function in php. The function travers through an array and inputs some values of the array in a new array. I am using array_push() to enter values in the new array and I have also tried to do it without using array_push. This is the part of the function that calls the recursive function
if ($this->input->post('id') != '') {
$id = $this->input->post('id');
global $array_ins;
$k=0;
$data['condition_array'] = $this->array_check($id, $menus['parents'], $k);
// trial
echo "<pre>";
print_r($menus['parents']);
print_r($data['condition_array']);die;
// trial
}
and this here is the recursive function
function array_check($val, $array_main, $k) {
// echo $val . "<br>";
$array_ins[$k] = $val;
echo $k . "<br>";
$k++;
// $array_ins = array_push($array_ins, $val);
echo "<pre>";
print_r($array_ins);
if ($array_main[$val] != '') {
for ($i = 0; $i < sizeof($array_main[$val]); $i++) {
$this->array_check($array_main[$val][$i], $array_main, $k);
}
// $k++;
}
I've been trying to fix this erorr for quite some time with no luck . I would really appreciate any help possible .
thanks in advance
Move the global $array_ins; statement into the function.
Pass the variable $array_ins as a parameter to function
function array_check($val, $array_main, $k,$array_ins) {
}
and call the function
$this->array_check($id, $menus['parents'], $k,$array_ins);
or
function array_check($val, $array_main, $k) {
global $array_ins;
}
usage of global is not recommended in php check it here Are global variables in PHP considered bad practice? If so, why?
The global keyword should be used inside of functions so that the variable will refer to the value in the outer scope.
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b; // 3
I am creating this array with the below code:
$ignored = array();
foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
$ignored[] = $ignored2;
}
and i want to check if any item inside the array is LIKE a variable. I have this so far:
if(in_array($data[6], $ignored)) {
but I'm not sure what to do with the LIKE
in_array() doesn't provide this type of comparison. You can make your own function as follows:
<?php
function similar_in_array( $sNeedle , $aHaystack )
{
foreach ($aHaystack as $sKey)
{
if( stripos( strtolower($sKey) , strtolower($sNeedle) ) !== false )
{
return true;
}
}
return false;
}
?>
You can use this function as:
if(similar_in_array($data[6], $ignored)) {
echo "Found"; // ^-search ^--array of items
}else{
echo "Not found";
}
Function references:
stripos()
strtolower()
in_array()
Well, like is actually from SQL world.
You can use something like this:
$ignored = array();
foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
$ignored[] = $ignored2;
if ( preg_match('/^[a-z]+$/i', $ignored2) ) {
//do what you want...
}
}
UPDATE: Well, I found this answer, may be it's what you need:
Php Search_Array using Wildcard
Here is a way to do it that can be customized fairly easily, using a lambda function:
$words = array('one','two','three','four');
$otherwords = array('three','four','five','six');
while ($word = array_shift($otherwords)) {
print_r(array_filter($words, like_word($word)));
}
function like_word($word) {
return create_function(
'$a',
'return strtolower($a) == strtolower(' . $word . ');'
);
}
http://codepad.org/yAyvPTIq
To add different checks, simply add more conditions to the return. To do it in a single function call:
while ($word = array_shift($otherwords)) {
print_r(find_like_word($word, $words));
}
function find_like_word($word, $words) {
return array_filter($words, like_word($word));
}
function like_word($word) {
return create_function(
'$a',
'return strtolower($a) == strtolower(' . $word . ');'
);
}
I created empty array and pushing val into it.
$var = array();
function printTag($tags) {
foreach($tags as $t) {
echo $t['token'] . "/" . $t['tag'] . " ";
if($t['tag'] == 'NN' OR $t['tag']== 'JJ'){
array_push($var, $t['token']) ;
}
}
echo "\n";
}
code looks fine for me but gives error:
array_push() expects parameter 1 to be array, null given in /var/www/html/postag/poscall.php on line 9
what is wrong here?
entire code:
<?php
// little helper function to print the results
include ("postag.php");
$var = array();
function printTag($tags) {
foreach($tags as $t) {
echo $t['token'] . "/" . $t['tag'] . " ";
if($t['tag'] == 'NN' OR $t['tag']== 'JJ'){
array_push($var, $t['token']) ;
}
}
echo "\n";
}
$tagger = new PosTagger('lexicon.txt');
$tags = $tagger->tag('The quick brown fox jumped over the lazy dog. this is really yummy and excellent pizza I have seen have really in love it it');
printTag($tags);
?>
Your $var = array(); statement is outside the function and out of the scope of the function. Put that inside the function and it'll remove the warning
function printTag($tags) {
$var = array();
foreach($tags as $t) {
echo $t['token'] . "/" . $t['tag'] . " ";
if($t['tag'] == 'NN' OR $t['tag']== 'JJ'){
array_push($var, $t['token']) ;
}
}
echo "\n";
}
The problem in your case is that $var is not in the scope of your function, so it gets implicitly declared as null (and this raises a notice too).
That said, this seems like a good case array_reduce():
$var = array_reduce($tags, function(&$result, $t) {
if (in_array($t['tag'], ['NN', 'JJ'])) {
$result[] = $t['token'];
}
// you could do some output here as well
return $result;
}, []);
It filters and maps at the same time and the return value is the array you want.
Alternatively, just declare $var inside the function and return it:
function printTag(array $tags)
{
$var = [];
foreach($tags as $t) {
// ...
}
return $var;
}
// ...
$var = printTag($tags);
I have this code that echoes values from an array. I'd like to be able to echo the variable elsewhere in my code though. I've tried wrapping a function around it and echoing the function but I can't get anything to work. Here's the code that I have now...
function team(){
if ( ($items = field_get_items('entityform', $entityform, 'field_team_members')) ) {
$values = array_map($items, function($x) { return $x['value']; });
$comma_separated = implode(', ', $values);
foreach ($items as $item) {
$members = $prefix . $item['safe_value'];
$prefix = ', ';
echo $members;
}
}
}
If I simply do team(); it outputs nothing, as well as echo team();. What am I doing wrong here?
Your team function doesn't return anything which is why echo team(); doesn't print anything.
See the documentation on functions for more info: http://php.net/manual/en/functions.returning-values.php
function team(){
$output = '';
if ( ($items = field_get_items('entityform', $entityform, 'field_team_members')) ) {
$values = array_map($items, function($x) { return $x['value']; });
$comma_separated = implode(', ', $values);
$prefix = '';
$members = '';
foreach ($items as $item) {
$members .= $prefix . $item['safe_value'];
$prefix = ', ';
}
$output = $members;
}
return $output;
}
To clarify what i wrote as a comment, i just created a small script:
<?php
function team () {
$string = "hi";
return $string;
}
echo team();
Functions cant work unless until they are called, so you have to call team(); in some way, once called it will for sure display what ever you are trying to echo. Also above function will not display anything unless you force fully exit in that function. Or return some value.
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.