Reputation: 85
Sorry for not using the right terminology, but given how basic my PHP level is, perhaps you will not mind so much.
A function for a plugin I am using allows arguments in order to selectively echo content:
<?php phpquote(argumentstring); ?>
An example of the argument string is e.g. auto_refresh=0&tags=a,b,c
I had always assumed it would be possible to use an array to build up a 'string' e.g. something like
<?php $arg=array( 'auto_refresh' => '0', 'tags' => 'a,b,c' );
phpquote($arg); ?>
And was therefore thinking I could bring in other content from another field e.g.
<?php
$fieldcontent = get_field("field_content");
$arg=array( 'auto_refresh' => '0', 'tags' => $fieldcontent );
phpquote($arg); ?>
However, this does not seem to work and so my two questions are:
Thanks in advance. I appreciate this may seem like a really basic question with incorrect terminology (sorry!) so hope it makes sense to the experts.
Upvotes: 2
Views: 92
Reputation: 366
You can use implode()
and array_map()
PHP functions to make an array to become an argument string:
<?php
$args = array( 'auto_refresh' => '0', 'tags' => 'a,b,c' );
function rb_map( $a, $b ) {
return $a . '=' . $b;
}
$arg_string = implode('&', array_map( 'rb_map', array_keys($args), $args ) );
//var_dump($arg_string);
?>
Upvotes: 2
Reputation: 3125
<?php
$arg=array( 'auto_refresh' => '0', 'tags' => 'a,b,c' );
echo urldecode(http_build_query($arg)); //output: auto_refresh=0&tags=a,b,c
?>
Is this what you want?
Check http_build_query for more information
Upvotes: 2
Reputation: 3923
Loop through the array and use the implode()
function for glueing pieces together.
manual
Or you can do something like this, too:
$argumentString= "";
foreach($arg as $k=>$v){
$argumentString.= $k.'='.$v.'&';
}
$argumentString = substr($argumentString,0,-1); //removes the last &
Upvotes: 2
Reputation: 5643
Whether or not you can use an array as the argument of a function depends on how that is defined / used in the function itself.
Consider this for example:
function test($var) {
print_r($var);
}
$bla = array(1 => "test me", 2 => "balbla");
test($bla);
(You can play with it here)
You can pass either a string or an array as an argument of the test
function as print_r
is able to handle both. If the function had echo
for example, and you passed an array to the function as argument, it would fail.
Upvotes: 1