Return concatenated string from function in PHP - php

In PHP, I have created an array that stores values that need to be concatenated in numerous ways numerous times, and so have created an accompanying function to carry out the concatenation when it is required. However, the function does not seem to return the values of the array, but will return the plain text parts of the string:
$my_array = array ("id" => "test");
$test = "First part " . $my_array['id'];
echo $test; // <-- returns "First part test"
function concatenate(){
$test_2 = "First part " . $my_array['id'];
return $test_2;
}
$use_function = concatenate();
echo $use_function; // <-- returns "First part". Does not include array information.
Any ideas on why this is happening or better methods of approaching this would be much appreciated. Thanks.

$my_array = array ("id" => "test");
$test = "First part " . $my_array['id'];
echo $test; // <-- returns "First part test"
function concatenate($my_array){
$test_2 = "First part " . $my_array['id'];
return $test_2;
}
$use_function = concatenate($my_array);
echo $use_function;
It's a minor mistake.. Please be careful, while calling function..

You cant use the $my_array-variable in this function! You have to make it global OR call function with array as argument:
Function:
function concatenate($arr, $string = "First Part "){ return $string . $arr['id']; }
Call: concatenate($my_array);

Try this
$my_array = array ("id" => "test");
function concatenate($my_array){
$test_2 = "First part " . $my_array['id'];
return $test_2;
}
$use_function = concatenate($my_array);
echo $use_function;
Output:
First part test

Try Using this code
$my_array = array ("id" => "test");
$test = "First part " . $my_array['id'];
echo $test; // <-- returns "First part test"
function concatenate($myArray){
$test_2 = "First part " . $myArray['id'];
return $test_2;
}
$use_function = concatenate($my_array);
echo $use_function;
or you can use this inside your function if this function is in a class:
$test_2 = "First part " . $this->my_array['id']
Your function is not aware of the my_array['id'] that's why it is unable to return anything

Related

What is the difference between $message and $$message in php? [duplicate]

Example is a variable declaration within a function:
global $$link;
What does $$ mean?
A syntax such as $$variable is called Variable Variable.
For example, if you consider this portion of code:
$real_variable = 'test';
$name = 'real_variable';
echo $$name;
You will get the following output:
test
Here:
$real_variable contains 'test'
$name contains the name of your variable: 'real_variable'
$$name mean "the variable thas has its name contained in $name"
Which is $real_variable
And has the value 'test'
EDIT after #Jhonny's comment:
Doing a $$$?
Well, the best way to know is to try ;-)
So, let's try this portion of code:
$real_variable = 'test';
$name = 'real_variable';
$name_of_name = 'name';
echo $name_of_name . '<br />';
echo $$name_of_name . '<br />';
echo $$$name_of_name . '<br />';
And here's the output I get:
name
real_variable
test
So, I would say that, yes, you can do $$$ ;-)
The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So, consider this example
$inner = "foo";
$outer = "inner";
The variable:
$$outer
would equal the string "foo"
It's a variable's variable.
<?php
$a = 'hello';
$$a = 'world'; // now makes $hello a variable that holds 'world'
echo "$a ${$a}"; // "hello world"
echo "$a $hello"; // "hello world"
?>
It creates a dynamic variable name. E.g.
$link = 'foo';
$$link = 'bar'; // -> $foo = 'bar'
echo $foo;
// prints 'bar'
(also known as variable variable)
I do not want to repeat after others but there is a risk using $$ :)
$a = '1';
$$a = 2; // $1 = 2 :)
So use it with head. :)
It evaluates the contents of one variable as the name of another. Basically it gives you the variable whose name is stored in $link.
this worked for me (enclose in square brackets):
$aInputsAlias = [
'convocatoria' => 'even_id',
'plan' => 'acev_id',
'gasto_elegible' => 'nivel1',
'rubro' => 'nivel2',
'grupo' => 'nivel3',
];
/* Manejo de los filtros */
foreach(array_keys($aInputsAlias) as $field)
{
$key = $aInputsAlias[$field];
${$aInputsAlias[$field]} = $this->request->query($field) ? $this->request->query($field) : NULL;
}

array member gets set to null after returning it

I have a Function a, which looks something like this:
function a(){
$myStr = "hello";
$arrParams = array();
$arrParams[] = "ssss";
$arrParams[] = "%".$_GET["tbField1"]."%";
echo implode(", ", $arrParams); //result: ssss, (textOfUserInput)
$retArr = array($myStr, $arrParams);
return $retArr;
}
$resArr = a();
echo $resArr[0]; //this one would still work
echo "hello" .$resArr[1] ."world"; //result: helloworld
if I execute this function, the echo prints out the two strings, which is supposed to be in there.
but if I call the function and save the returned array in a variable b, i have access to b[0], but b[1] remains empty.
Can somebody help me please?

Behavior of return and echo in php

I am confused about how the program is working; the code should print A, bB but it is showing bA,B
class SampleClass {
public $a = "A";
protected $b = array ("a" => "A", "b" => "B", "c" => "C");
public function __get($v){
echo "$v";
return $this->b[$v];
}
}
$m = new SampleClass();
echo $m->a . ", " . $m->b;
This makes perfect sense really. Let's think about the execution order:
Before PHP can ECHO your requested string, it must evaluate it first (i.e. the $m->a . ", " . $m->b part)
So at this point, the parser tries to resolve $m->a and $m->b, it resolves the first, but the 2nd fails, so we go to the magic method.
The magic method echos something (the first `b), and then resolves itself to B.
Now, we need to finish what we started (the original echo).
So what do we have?
resolve the $m->b(echo in b in the process).
echo "A,B"
combine it all together?
bA,B
This is odd isn't it but it isn't doing what you think it is doing.
Running this code does something different.
class SampleClass {
public $aaa = "A";
protected $b = array ("a"=> "A", "b" => "B", "c" => "C");
public function __get($v){
echo "$v";
return $this->b[$v];
}
}
$m = new SampleClass();
echo "[" . $m->a. ", ". $m->b. ", ". $m->c . "]";
Output is:
abc[A, B, C]
Your original __get does not get called when you do $m->a since there is a variable 'a' anyhow. It is only called as a last resort so you should write your own specific 'getter' function instead.

PHP array runs function and pass variable to it

I am coding a bot for a game and I am now coding the handlers I want to call my array so it runs the function.
$handlers = array(
"x" => function()
);
function function($m)
{
echo "Var: " . $m . "\n";
}
When I call handlers I tried it like this:
$handlers("x");
So how can I pass the variable to the function.
What you need is the call_user_func function. Besides, in your $handlers array, the name of the function must be in quotation marks and you can not use the reserved keyword function as the name of the function! and you may access the array element using [] operator:
$handlers = array(
"x" => '_function'
);
function _function($m)
{
echo "Var: " . $m . "\n";
}
call_user_func($handlers['x'], "hello :)");
For completeness, you can do it this way as well:
$handlers = array(
"x" => 'test'
);
function test($m) {
echo "Var: " . $m . "\n";
}
$handlers['x']("testing...");

How to use one array in two functions in PHP?

I have an array with the following content:
$array_test = array ("User1"=>"Test1",
"User2"=>"Test2");
First column shall be $uservalue and second $testvalue in the functions. It worked, when I use a single column array for the first function loop through the array in the function.
And I would like to use this array in the following two functions.
The first column of the array should be use as $uservalue.
function do_show(array $options) {
global $showresult, $master;
$cn = $uservalue;
$config = $options["config"]->value;
// an empty show tag
$show = new SimpleXMLElement("<show/>");
// add the user tag
$user = $show->addChild("user");
// add the "cn" attribute
$user->addAttribute("cn", $cn);
if ($config)
$user->addAttribute("config", "true");
print "cmd: " . htmlspecialchars($show->asXML()) . "\n";
// do it
$showresult = $masterPBX->Admin($show->asXML());
print "result: " . htmlspecialchars($showresult) . "\n";
}
Second function where I would like to use the second Column of the array as Value for $testvalue:
function do_modify(array $options) {
global $showresult, $master;
$mod = $testvalue;
$modify = new SimpleXMLElement("$showresult");
$user = $modify->user;
$path = explode("/device/hw/", $mod);
$srch = $user;
$nsegments = count($path);
$i = 1;
foreach ($path as $p) {
if ($i == $nsegments) {
// last part, the modification
list($attr, $value) = explode("=", $p);
$srch[$attr] = $value;
} else {
$srch = $srch->$p;
}
$i++;
}
// wrap the modified user tag in to a <modify> tag
$modify = new SimpleXMLElement("<modify>" . $user->asXML() . "</modify>");
print "cmd: " . htmlspecialchars($cmd = $modify->asXML()) . "\n";
$result = $master->Admin($cmd);
print "result: " . htmlspecialchars($result);
}
How can I archieve this? I found these two functions in the wiki of the software I would like to implement this... Therefore I know that using global variables is not a good option.
You can split your array into two arrays using following code and pass appropriate array to relevant function.
$array_test = array ("User1"=>"Test1",
"User2"=>"Test2");
$array_users = array_keys($array_test);
$array_tests = array_values($array_test);
Here is the link for details on both array_values and array_keys functions.
Pass the array as a function parameter to both functions...or make the array global. Pass by reference if you want to change original array (your array changes made inside the function to be visible outside of the function).

Categories