PHP: concatenation of multidimensional array elements - php

I want to concatenate one element of a multidimensional array with some strings.
<?
$string1 = 'dog';
$string2 = array
(
'farm' => array('big'=>'cow', 'small'=>'duck'),
'jungle' => array('big'=>'bear', 'small'=>'fox')
);
$string3 = 'cat';
$type = 'farm';
$size = 'big';
$string = "$string1 $string2[$type][$size] $string3";
echo($string);
?>
By using this syntax for $string, I get:
dog Array[big] cat
I would like not to use the alternate syntax
$string = $string1 . ' ' . $string2[$type][$size] . ' ' . $string3;
which works.
What's wrong with "$string1 $string2[$type][$size] $string3"?

Use the "complex syntax":
$string = "$string1 {$string2[$type][$size]} $string3";
PHP's variable parsing is quite simple. It will recognize one level array access, but not more level. By enclosing the expression in {} you explicitly state which part of the string is a variable.
See PHP - Variable parsing.

I'm not a fan of complex syntax, or variable parsing in strings. Normally I would use the "alternate" syntax you described. You could do this as well:
$string = implode(' ', array($string1, $string2[$type][$size], $string3));

Use this:
$string = "$string1 {$string2[$type][$size]} $string3";

Related

Seperate values from string in between characters in php

I have a string ("$big_string") in php with is combination of small section of strings("$string") like this one "-val1(sec1)-", for eg :
$string1="-val1(sec1)-";
$string2="-val2(sec2)-";
$string3="-val3(sec3)-";
$big_string=$string1.$string2.$string3;
How can I separate values from $big_string to an array-like
the val1.. and so on values are between '-' & '('
and the sec1... and so on values are beteen '(' & ')-'
$array[0][0]="val1";
$array[0][1]="sec1";
$array[1][0]="val2";
$array[1][1]="sec2";
$array[2][0]="val3";
$array[2][1]="sec3";
Edit: I received the $big_string as input, above code is for ref that how $big_string is constructed.
You could use preg_match_all:
$string1 = "-val1(sec1)-";
$string2 = "-val2(sec2)-";
$string3 = "-val3(sec3)-";
$big_string = $string1 . $string2 . $string3;
if (preg_match_all('/-([^(]+)\(([^)]+)\)-/', $big_string, $matches, PREG_SET_ORDER)) {
$result = array_map(static fn($match) => array_slice($match, 1), $matches);
print_r($result);
}
If you're using PHP < 7.4, the line with $result can be changed into this:
$result = array_map(static function ($match) {
return array_slice($match, 1);
}, $matches);
Demo
I like to keep my code simple, using basic PHP functions. Something like this:
$big_string = '-val1(sec1)--val2(sec2)--val3(sec3)-';
$val_sec_array = explode('--', trim($big_string, '-'));
foreach ($val_sec_array as $val_sec) {
$array[] = [strstr($val_sec, '(', TRUE),
trim(strstr($val_sec, '('), '()')];
}
print_r($array);
The first line uses trim() to trim off the excess '-' at the begin and end of the $big_string and then explodes the remaining string into an array on each '--' it encounters.
The foreach loop then takes that array and uses strstr to first get the section before the '(' from the string and then the section after the '('. The '(' and ')' are then trimmed off the latter section. The two values then form an array [ ... , ... ] and are stored in the main array.
This is funny, saying it like this makes it sound more complex than it really is. Just look in the manual how this works:
explode()
trim()
foreach
strstr()
arrays

Creating a String from an Array in PHP

I'm trying to create a string out of several array values like so:
$input = array("1140", "1141", "1142", "1144", "1143", "1102");
$rand_keys = array_rand($input, 2);
$str = "$input[$rand_keys[0]], $input[$rand_keys[1]]";
However, in the third line, I get this error:
Unexpected '[' expecting ']'
I thought that by converting the array to a value I would be able to use it in my string. What am I doing wrong with my syntax?
If you just want to fix your code, simply adjust that one line to this line:
$str = $input[$rand_keys[0]] .', '. $input[$rand_keys[1]];
Here are a couple of other nicer solutions:
shuffle($input);
$str = $input[0] .', '. $input[1];
Or:
shuffle($input);
$str = implode(', ',array_slice($input,0,2));
When you want to expand more than simple variables inside strings you need to use complex (curly syntax). Link to manual. You need to scroll down a little in the manual. Your last line of code will look like this:
$str = "{$input[$rand_keys[0]]}, {$input[$rand_keys[1]]}";
But you could also use implode to achieve the same result.
$str = implode(', ', [$rand_keys[0], $rand_keys[1]]);
It's up to you.

Parse variables in PHP string

NOTE: Eval is used here in total knowledge, the string parsed is entered by an administrator only, and the purpose is to store instructions in database, without restrictions to the instructions.
If you have a good alternative, it is always appreciated, but don't just say "eval is bad".
I have a String in PHP, for example
$myString = "(35*$var1*64)/$var2";
I want to eval() this string, but before, I want to modify all the variables in the string like this:
$var2 -> $_POST['var2']
There may or may not be a blank space after the variable in $myString .
When I eval $myString, PHP throws an error "Undefined variable $var1". PHP read the string and parse the variables, so I guess there should be a way to parse all the variables in the string.
The output should be:
$myStringParsed = "(35*$_POST['var1']*64)/$_POST['var2']";
or an equivalent.
Not maybe the best solution, but you can preprocess $_POST variable and generate $variablesString like this:
$variablesString = '';
foreach($_POST as $key => $val) {
$variablesString .= '$' . $key . ' = ' . $val . ';' . PHP_EOL;
}
eval($variablesString . PHP_EOL . $myString)
For string support you can check if $val is string, and if yes - wrap it with quotes.
Second way
$myString = 'return (35 * $var1 * 64) / $var2;';
$re = "/\\$(\\w*)/im";
preg_match_all($re, $myString, $matches);
foreach($matches[1] as $match) {
$search = '$' . $match;
$replace = '$_POST[\'' . $match . '\']';
$myString = str_replace($search, $replace, $myString);
}
echo eval($myString);
You can check it here
Assuming you mean....
$myString = '(35*$var1*64)/$var2';
The a more robust solution (consider $myvar10) than that suggested by ASGM is:
$replace=array(
'/\b\$var1\b/'=>$_POST['var1'],
'/\b\$var2\b/'=>$_POST['var2'],
...
);
$interpolated=preg_replace(array_keys($replace)
, $replace, $myString);
Note that I would recommend that you interpolate the string with literals rather than substituting one place holder for another. In addition to eliminating unnecessary processing, it also means you can check the content of the resulting string to ensure it only contains digits and operators (and a restricted number of functions if appropriate).
You are using wrong string enclosing quotes. Use '(35*$var1*64)/$var2':
//$var1 = $_POST['var1'];
//$var2 = $_POST['var2'];
$var1 = '10';
$var2 = '20';
$myString = 'return (35 * $var1 * 64) / $var2;';
echo eval($myString);
//1120
Working example of eval
If you want to take any variable from POST, than you can use extract() to get array keys as variables with associated values:
<?php
// Change it to real $_POST
$POST = [
'var1' => '10',
'var2' => '20',
];
extract($POST, EXTR_SKIP);
$myString = 'return (35 * $var1 * 64) / $var2;';
echo eval($myString);

Adding something to the start of a variable?

I am looking for some code that allows you to add +44 onto the beginning of my $string variable.
So the ending product would be:
$string = 071111111111
+44071111111111
Your $string variable isn't actually a string in this scenario; it's an integer. Make it a string by putting quotes around it:
$string = "071111111111"
Then you can use the . operator to append one string to another, so you could do this:
$string = "+44" . $string
Now $string is +44071111111111. You can read more about how to use the . (string concatenation operator) on the PHP documentation here.
Other people's suggestions of just keeping $string as an integer wouldn't work: "+44" . 071111111111 is actually +447669584457. Due to the 0 at the start of the number, PHP converts it to an octal number rather than a decimal one.
You can combine strings by .
$string = '+44'.$string;
You can use universal code, which works with another parameters too.
<?php
$code = "+44";
$string = "071111111111";
function prepend(& $string, $code) {
$test = substr_replace($string, $code, 0, 0);
echo $test;
}
prepend($string, $code);
?>

Add double quote between text seperated by comma [duplicate]

This question already has answers here:
PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
(2 answers)
Closed 8 years ago.
I'm trying to figure out how to add double quote between text which separates by a comma.
e.g. I have a string
$string = "starbucks, KFC, McDonalds";
I would like to convert it to
$string = '"starbucks", "KFC", "McDonalds"';
by passing $string to a function. Thanks!
EDIT: For some people who don't get it...
I ran this code
$result = mysql_query('SELECT * FROM test WHERE id= 1');
$result = mysql_fetch_array($result);
echo ' $result['testing']';
This returns the strings I mentioned above...
Firstly, make your string a proper string as what you've supplied isn't. (pointed out by that cutey Fred -ii-).
$string = 'starbucks, KFC, McDonalds';
$parts = explode(', ', $string);
As you can see the explode sets an array $parts with each name option. And the below foreach loops and adds your " around the names.
$d = array();
foreach ($parts as $name) {
$d[] = '"' . $name . '"';
}
$d Returns:
"starbucks", "KFC", "McDonalds"
probably not the quickest way of doing it, but does do as you requested.
As this.lau_ pointed out, its most definitely a duplicate.
And if you want a simple option, go with felipsmartins answer :-)
It should work like a charm:
$parts = split(', ', 'starbucks, KFC, McDonalds');
echo('"' . join('", "', $parts) . '"');
Note: As it has noticed in the comments (thanks, nodeffect), "split" function has been DEPRECATED as of PHP 5.3.0. Use "explode", instead.
Here is the basic function, without any checks (i.e. $arr should be an array in array_map and implode functions, $str should be a string, not an array in explode function):
function get_quoted_string($str) {
// Here you will get an array of words delimited by comma with space
$arr = explode (', ', $str);
// Wrapping each array element with quotes
$arr = array_map(function($x){ return '"'.$x.'"'; }, $arr);
// Returning string delimited by comma with space
return implode(', ', $arr);
}
Came in my mind a really nasty way to do it. explode() on comma, foreach value, value = '"' . $value . '"';, then run implode(), if you need it as a single value.
And you're sure that's not an array? Because that's weird.
But here's a way to do it, I suppose...
$string = "starbucks, KFC, McDonalds";
// Use str_replace to replace each comma with a comma surrounded by double-quotes.
// And then shove a double-quote on the beginning and end
// Remember to escape your double quotes...
$newstring = "\"".str_replace(", ", "\",\"", $string)."\"";

Categories