i want to call function store inside array but before i do it i want to check if it is function,string or any other type.
please take a look at my code
$a=new stdClass();
$array = array(function() {
return "Bhavik Patel";
}, "1213",$a);
foreach ($array as $key => $value) {
if (is_object($value)) {
echo $value() . "<br/>";
} else {
echo $value . "<br/>";
}
}
by doing this i can check if value is object then i call it but if i pass object it gives (pf course this will give error)
my intention is to find if value is function then call it.
To check specifically for anonymous functions you can test the value against \Closure like so:
if ($value instanceof \Closure) {
echo $value(), "\n";
} else {
echo $value;
}
The problem with is_callable() is that if your value is "explode", it will return true which is obviously not what you want.
is_callable() will help you, but notice that if you pass an array like this
array('object or class','method')
is_callable() return true, so you'd better to check it isn't an array
if (is_callable($value) && !is_array($value)) {.....}
see is_callable
Try [is_callable][1] in PHP. I have tested it, it works for me.
Related
I use array_walk_recursive to apply htmlspecialchars on my array value, but it didn't work, htmlspecialchars works when I use it manully;
Here is my code:
$new[] = "<a href='test'>Test</a><li><div>";
var_dump(array_walk_recursive($new,'htmlspecialchars')); // true
var_dump($new) ; // no change
That is because the original array is not modified unless you modify it yourself in the callback function.
Your callback function is basically:
function($item, $key) {
htmlspecialchars($item);
}
So while the function is called, nothing is stored and the original array is not changed.
If you want to modify the value in the function, you can pass it by reference:
function(&$item, $key) {
$item = htmlspecialchars($item);
}
So the result would look like:
$new[] = "<a href='test'>Test</a><li><div>";
array_walk_recursive($new, function(&$item, $key) {
$item = htmlspecialchars($item);
});
var_dump($new) ; // change!
You can of course define a separate function if you would prefer that.
In the definition of array_walk_recursive:
array_walk_recursive — Apply a user function recursively to every
member of an array
So you need to create a user defined function that uses htmlspecialchars like this:
$new[] = "<a href='test'>Test</a><li><div>";
array_walk_recursive($new, "specialChars");
var_dump($new);
function specialChars(&$value) {
$value = htmlspecialchars($value);
}
And this will print:
array (size=1)
0 => string '<a href='test'>Test</a><li><div>' (length=56)
I am new to PHP and hope someone can help me with this.
I have the following function to which I can pass an itemID (unique integer) which it will then use to return the corresponding translation from a previously created array (this is just the final part).
PHP function (saved in my header file):
function fetchTransMain($trans, $itemID){
foreach($trans as $key => $val){
if($val["ID"] == $itemID){
echo $val["trans"];
}
}
}
This works as intended as long as I refer to the function anywhere on an HTML page as follows.
Echoing result on HTML page (working):
echo fetchTransMain($trans, someID);
However, I have certain scenarios where instead of echoing the result to the page I need to save it as a variable. I tried the following but this still echoes it somewhere at the top of the screen.
Save result to variable instead of echoing it (not working):
$someVariable = fetchTransMain($trans, someID);
Can someone tell me how I can use this function both to echo the result (working part) and to save it to a variable alternatively (not working part) - as needed ?
Many thanks in advance,
Mike
Just return the value in the function instead of echoing it:
function fetchTransMain($trans, $itemID){
foreach($trans as $key => $val){
if($val["ID"] == $itemID){
return $val["trans"];
}
}
}
Then, when you want to print it you do:
echo fetchTransMain($trans, someID);
Otherwise you do:
$someVariable = fetchTransMain($trans, someID);
Can someone tell me how I can use this function both to echo the result (working part) and to save it to a variable alternatively.
Some functions like print_r take an optional parameter to indicate if it should return the value, or just echo it, so this is a fair question. Here is the function signature for print_r:
mixed print_r ( mixed $expression [, bool $return = false ] )
If you'd like this functionality too, try passing in an optional 3rd parameter to indicate if you want your function to echo or return a value.
function fetchTransMain($trans, $itemID, $echo = false){
foreach($trans as $key => $val){
if($val["ID"] == $itemID){
if(!$echo) {
echo $val["trans"]; // Echo the value
} else {
return $val["trans"]; // Return the value
}
}
}
}
Edit: It's much simpler to just return the value and echo it outside the function, but my answer is intended to be faithful to your exact question.
function fetchTransMain($trans, $itemID){
foreach($trans as $key => $val){
if($val["ID"] == $itemID){
$tobePrint.= $val["trans"];
}
}
return $tobePrint;
}
and use it with :
print fetchTransMain($trans, $itemID)
or
$variable = fetchTransMain($trans, $itemID)
You need to return a value from function.
assuming you might have only one possible match try this.
function fetchTransMain($trans, $itemID){
foreach($trans as $key => $val){
if($val["ID"] == $itemID){
return $val["trans"];
}
}
}
and then call your function
$someVariable = fetchTransMain($trans, $someID);
and then echo returned value.
echo $someVariable;
The most flexible and extensible way to do this is to use the output buffer functions http://php.net/manual/en/ref.outcontrol.php.
function fetchTransMain($trans, $itemID, $echo){
$str="";
ob_start();
foreach($trans as $key => $val){
if($val["ID"] == $itemID){
echo $val["trans"]; // Echo the value
}
}
$str = ob_get_buffer();
if($echo) ob_end_flush();
else ob_end();
return $str;
}
The code above isn't tested for functional or syntactical correctness, but it should work as-is or quite similar.
I've got a PHP object. One of the values within the object is in array. I'm trying to get a foreach to just read the array within the object but it doesn't seem to be working.
PHP:
foreach ($object->ArrayName as $value) {
echo $value;
}
is there any way of doing this?
well, if you have an object but you don't know which property is an array, you need to catch them all and verify if they are an array:
// get each value of the object and call it as property
foreach(get_object_vars($object) as $property) {
// if this property is an array...
if (is_array($property) {
// ... access to every value of that array
foreach($property as $value) {
// $property is your array and $value is every value
// here you can execute what you need
}
}
}
Use
is_array($obj)
to validate whether it's an array or not.
you said your php object contains arrays, hence you need to use 2 foreach loops like this.
<?php
foreach($object->ArrayName as $value) {
foreach($value as $item) {
echo $item;
}
}
?>
if the loop is withing the object wich mean inside the class use $this instead :
foreach ($this->ArrayName as $value) {
echo $value;
}
I couldn't find anything that answers my question so here it is:
I need to have a foreach loop to take each function inside of an array and run each and check if it returns true, simple enough. Like this:
$array_name = array(function1(),function2(),function3());
foreach($array_name as &$value) {
/* run each function */
/* checks if it returns true */
}
This may be so easy I just don't see it, but I can't find any definitive documentation on how to correctly implement this.
$array_name = array('function1', 'function2', 'function3');
foreach($array_name as $value) {
if($value()) {
// do stuff if the function returned a true-ish value
}
}
Another option to call the function would be call_user_func($value).
Try it:
$array_name = array('function1','function2','function3');
foreach($array_name as &$value) {
if(function_exists($value) && ($value())) {
//function exists and it returns true
}
}
Try to adopt things from : http://php.net/manual/en/functions.variable-functions.php
foreach($functionName as $arg) {
$arg();
}
But as you question contains:
$array_name = array(function1(),function2(),function3());
Make sure "function1()" is used in your array. So we can have:
foreach($functionName as $arg) {
$check = $arg;
if($check != false){
//Do stuff here
}else{
//Do stuff here
}
}
I need to create a column-system for Wordpress with shortcodes, which is not a problem, but I'm trying to make it with less code.
I have an array with the data needed, I loop through it, create a unique-named function and set it as shortcode-function. The third step is a mystery. How can I create a function from a variable.
Here's an example, how it should be done:
$data[] = "first";
$data[] = "second";
foreach($data as $key => $value) {
function $value($atts,$content) {
return '<div class="'.$value.'">'.$content.'</div>';
}
add_shortcode($value,$value);
}
However, it seems that it's not possible to make it work like that in PHP. Is there any way to make this work, as I would not want to write all the (identical) functions separated. I could make the shortcode something like [col first]text[/col] but the client wants to have different names for every one of them.
you can use the double dollar syntax to use the value of a variable as a variable identifier,
Example:
$variable = "test";
$$variable = "value of test"
echo $test; //or echo $$variable;
I have never tried but you way want to try:
foreach($data as $key => $value)
{
function $$value($atts,$content)
{
}
add_shortcode($value,$value);
}
or a function like create_function
if your using PHP 5.3 or greater then you can do something like so:
$$value = function()
{
}
which should work fine
I'm not sure how WP invocates the functions, but if it uses call_user_func then you might cheat by using an object with virtual methods:
class fake_functions {
function __call($name, $params) {
return '<div class="'.$name.'">'.$params[1].'</div>';
}
}
$obj = new fake_functions();
foreach ($data as $value) {
add_shortcode($value, array($obj,$value));
}