convert trim logic into function has unexpected result [duplicate] - php

This question already has answers here:
Are PHP Variables passed by value or by reference?
(16 answers)
Closed 12 months ago.
Here's some test data in an associative array for which I'm trying to build a trim function:
$header = [
'comment1' => ' abc ',
'comment2' => 'abc ',
'comment3' => ' abc',
'comment4' => 'abc'
];
The foreach line code below works correctly to trim the values within the array and keep the original keys:
echo '<pre>' . print_r($header, 1) . '</pre>';
var_dump($header);
foreach ($header as &$val) $val = trim($val); // <--- this is the line that does the trimming
echo '<pre>' . print_r($header, 1) . '</pre>';
var_dump($header);
Outputs:
However, when I attempt to make the foreach into a function like so
function trimValues($array) {
foreach ($array as &$value) {
$value = trim($value);
}
}
And call it like this
echo '<pre>' . print_r($header, 1) . '</pre>';
var_dump($header);
trimValues($header); // <--- this is the line that calls the trimming function
echo '<pre>' . print_r($header, 1) . '</pre>';
var_dump($header);
The output shows the trim didn't work
What am I overlooking here?

Yep, I see the small detail that was overlooked. The & was missing in the first line of the function -
function trimValues(&$array) { ...

Related

Resolve a multi dimensional array into fully specified endpoints

I need to turn each end-point in a multi-dimensional array (of any dimension) into a row containing the all the descendant nodes using PHP. In other words, I want to resolve each complete branch in the array. I am not sure how to state this more clearly, so maybe the best way is to give an example.
If I start with an array like:
$arr = array(
'A'=>array(
'a'=>array(
'i'=>1,
'j'=>2),
'b'=>3
),
'B'=>array(
'a'=>array(
'm'=>4,
'n'=>5),
'b'=>6
)
);
There are 6 end points, namely the numbers 1 to 6, in the array and I would like to generate the 6 rows as:
A,a,i,1
A,a,j,2
A,b,2
B,a,m,3
B,a,n,4
B,b,2
Each row contains full path of descendants to the end-point. As the array can have any number of dimensions, this suggested a recursive PHP function and I tried:
function array2Rows($arr, $str='', $out='') {
if (is_array($arr)) {
foreach ($arr as $att => $arr1) {
$str .= ((strlen($str)? ',': '')) . $att;
$out = array2Rows($arr1, $str, $out);
}
echo '<hr />';
} else {
$str .= ((strlen($str)? ',': '')) . $arr;
$out .= ((strlen($out)? '<br />': '')) . $str;
}
return $out;
}
The function was called as follows:
echo '<p>'.array2Rows($arr, '', '').'</p>';
The output from this function is:
A,a,i,1
A,a,i,j,2
A,a,b,3
A,B,a,m,4
A,B,a,m,n,5
A,B,a,b,6
Which apart from the first value is incorrect because values on some of the nodes are repeated. I have tried a number of variations of the recursive function and this is the closest I can get.
I will welcome any suggestions for how I can get a solution to this problem and apologize if the statement of the problem is not very clear.
You were so close with your function... I took your function and modified is slightly as follows:
function array2Rows($arr, $str='', $csv='') {
$tmp = $str;
if (is_array($arr)) {
foreach ($arr as $att => $arr1) {
$tmp = $str . ((strlen($str)? ', ': '')) . $att;
$csv = array2Rows($arr1, $tmp, $csv);
}
} else {
$tmp .= ((strlen($str)? ', ': '')) . $arr;
$csv .= ((strlen($csv)? '<br />': '')) . $tmp;
}
return $csv;
}
The only difference is the introduction of a temporary variable $tmp to ensure that you don't change the $str value before the recursion function is run each time.
The output from your function becomes:
This is a nice function, I can think of a few applications for it.
The reason that you are repeating the second to last value is that in your loop you you are appending the key before running the function on the next array. Something like this would work better:
function array2Rows($arr, &$out=[], $row = []) {
if (is_array($arr)) {
foreach ($arr as $key => $newArray) {
if (is_array($newArray)) {
$row[] = $key; //If the current value is an array, add its key to the current row
array2Rows($newArray, $out, $row); //process the new value
} else { //The current value is not an array
$out[] = implode(',',array_merge($row,[$key,$newArray])); //Add the current key and value to the row and write to the output
}
}
}
return $out;
}
This is lightly optimized and utilizes a reference to hold the full output. I've also changed this to use and return an array rather than strings. I find both of those changes to make the function more readable.
If you wanted this to return a string formatted similarly to the one that you have in your function, replace the last line with
return implode('<br>', $out);
Alternatively, you could do that when calling, which would be what I would call "best practice" for something like this; e.g.
$result = array2Rows($arr);
echo implode('<br>', $result);
Note, since this uses a reference for the output, this also works:
array2Rows($arr, $result);
echo implode('<br>', $result);

Implode with default value if no values

I want to show dash(-) if my array is empty after imploding it. Here below is my try so far.
Result with Data in Array -> https://repl.it/HIUy/0
<?php
$array = array(1,2);
$result = array();
foreach ($array as $curr_arr) {
$result[] = $curr_arr;
}
echo 'Array With Data - ' . implode(',', $result);
//Result : Array With Data : 1,2
?>
Result without Data in Array -> https://repl.it/HIVE/0
<?php
$array = array();
$result = array();
foreach ($array as $curr_arr) {
$result[] = $curr_arr;
}
echo 'Array Without Data - ' . implode(',', $result);
//Result : Array With Data - :
?>
As you can see in the second result, I am unable to print anything as my array was blank hence I was unable to print anything.
However, I want to print Dash(-) using implode only by using something like array_filter which I already tried but I am unable to do so. Here I have tried this https://repl.it/HIVP/0
<?php
$array = array();
$result = array();
foreach ($array as $curr_arr) {
$result[] = $curr_arr;
}
echo 'Array With Data : ' . implode(',', array_filter($result));
//Result : Array With Data :
?>
Can someone guide me how to achieve this ?
Thanks
You can check if your array is empty and then return/ echo a Dash:
if(!empty($array)){
// Array contains values, everything ok
echo 'Array with data - ' . implode('yourGlueHere', $array);
} else {
// Array is empty
echo 'Array without data -';
}
If you want to have it in one line, you could do something like the following:
echo 'Array with' . empty($array) == false ? '' : 'out' . 'data - ' . empty($array) == false ? implode('glue', $array) : '';
Answers posted by Tobias F. and Gopi Chand is correct.
Approach 1:
I'd suggest you going this way would help you (Basically using ternary operator).
As here is no other way of doing this using just implode function.
echo empty($result) ? '-' : implode(',',$result);
Approach 2
Using a helper function like this.
function myImpllode($glue = "", $array = [])
{
if(!empty($array)){
// Array contains values, everything ok
return implode($glue, $array);
} else {
// Array is empty
return '-';
}
}

preg_match/regex format needed

I have the below post fields submitted and I am trying to get the value of each of the numbers in the form field for the Quantity. Can someone help me with the regexp? I am trying to get each of the numbers in a variable.
FORMAT
Quantity_{Category}_{Product}_{Item}
POST FIELDS SUBMITTED
[submitted] => 1
[Quantity_12038_16061_24960] => 1
[Quantity_12037_16060_24959] => 2
[btnBuyNow] => Next Step
PHP CODE
foreach ($_POST as $key => $value) {
if (preg_match('/^Quantity_(\d+)$/', $key, $matches)) {
echo 'Key:' . $key . '<br>';
echo 'Matches:' . $matches . '<br>';
echo '<hr>';
}
}
Use preg_match() docs for this purpose, and that is a sample of how the code would look like:
$subject="Quantity_12038_16061_24960";
$pattern='/Quantity_(\d+)_(\d+)_(\d+)/';
preg_match($pattern, $subject, $matches);
echo $matches[0]; //12038 {Category}
echo $matches[1]; //16061 {Product}
echo $matches[2]; //24960 {Item}
you can see how this regex is performing here.
As the question is stated, regex is not needed:
foreach($_POST as $key => $val) {
if(strpos($key, 'Quantity') === 0) {
$results = explode('_', $key);
print_r($results);
}
}
To get rid of the Quantity string for whatever reason just unset($results[0]);.

How to use explode function in PHP?

I want to spit my string in to 2 pieces, I know that I have to use explode function in PHP.
Then I want to apply strtolower to my first element, and apply strtoupper for my last element, I just could figure it out where is the pieces are stored after splitting them ?
What I have tried ?
// $value[0] = "8000297C-1360598144";
echo $value[0] . "<br>";
dd(explode('-', $value[0]));
echo "<br>";
The "pieces" are not stored, but returned as the return value:
echo $value[0] . "<br>";
$pieces = explode('-', $value[0]);
echo strtolower($pieces[0]);
echo "<br>";
echo strtoupper($pieces[1]);
$value[0] = "8000297C-1360598144";
$value[0] = explode("-",$value[0]);
$value[0][0] = strtolower($value[0][0]);
$value[0][1] = strtoupper($value[0][1]);
From this, print_r($value); will output
Array
(
[0] => Array
(
[0] => 8000297c
[1] => 1360598144
)
)
// $value[0] = "8000297C-1360598144";
echo $value[0] . "<br>";
$elements = explode('-', $value[0]);
//
$elementzero = isset($elements[0]) ? $elements[0] : null;
$elementone = isset($elements[1]) ? $elements[1] : null;
echo strtolower($elementzero);
echo strtoupper($elementone);
If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.
You can also do it like this:
$value[0] = "8000297C-1360598144";
list($first, $second) = explode('-', $value[0]);
echo strtolower($first) . PHP_EOL;
echo strtoupper($second) . PHP_EOL;
Best,

Convert String to variable in PHP inside function argument

below is the code I have created. My point here is to convert all strings inside the function argument.
For example, fname('variable1=value1&variable2=value2'); I need to convert variable1 & variable2 into ang variable as $variable1, $variable2 instead parsing a plain text. I found out eval() function is useful but it only takes one string which is the "variable1" and its value.
function addFunction($arg){
echo eval('return $'. $arg . ';');
}
addFunction('variable1=value1&variable2=value2');
Now the problem is I got this error "Parse error: syntax error, unexpected '=' in D:\xampp\htdocs...\index.php(7) : eval()'d code on line 1". But if I have only one variable and value inside the function argument it works perfect, but I need to have more parameters here. Is this possible to do this thing or is there any other way to count the parameters before it can be evaluated?
Thank you,
function addFunction($arg)
{
parse_str($arg, $args);
foreach ($args as $key => $val) {
echo $key , " --> " , $val, "\n";
}
}
addFunction('variable1=value1&variable2=value2');
Output
variable1 --> value1
variable2 --> value2
You can also use
function addFunction($arg)
{
parse_str($arg);
echo $variable2; // value2
}
addFunction('variable1=value1&variable2=value2');
You are trying to create a variable with this name:
$variable1=value1&variable2=value2
You need to explode it at the & to get just the desired future variable names.
function addFunction($arg){
echo eval('return $'. $arg . ';');
}
$string = 'variable1=value1&variable2=value2';
$array = explode('&', $string);
foreach($array as $part)
{
addFunction($part);
}
You can break a string up using the PHP explode function, and then use eval to evaluate each variable indepedently.
$myvars = explode ('$', 'variable1=value1&variable2=value2');
$myvars is then an array which you can parse and feed to eval as needed.
Perhaps you can use explode()?
$varArr = explode("&",$arg);
foreach ($varArr as $varKey=>$varVal) {
echo eval('return $'.$varKey.'='.$varVal.';');
}
You need split the $arg at & to get each variable and then again at = to get each variable and value.
$arg = 'variable1=value1&variable2=value2';
$vars = explode('&', $arg);
foreach ($vars as $var) {
$parts = explode("=", $var);
echo eval('return $'. $parts[0] . '='. $parts[1] . ';');
}
Something like this:
function addFunction($arg)
{
$varArr = explode("&",$arg);
$varResponse ="";
foreach ($varArr as $varKey=>$varVal) {
$varResponse = $varResponse."$".$varVal.";";
}
return $varResponse;
}
echo addFunction('variable1=value1&variable2=value2');
Saludos ;)

Categories