I have array of 3000 elements which are like this
Array[0]= 405adc92-cfad-4be6-9ad2-ca363eda4933
Array[1]= 405adc92-cfad-4be6-9ad2-ca363eda4933
And I need to pass a variable in a function which require only a single quote at the beginning. I tried a solution on web which is pasting single quote on beginning and end aswell .like this
function add_quotes($str) {
return sprintf("'%s'", $str);
}
$csv = implode(',', array_map('add_quotes', $a));
$myArray = explode(',', $csv);
echo gettype($myArray[1]);
so answer is like this
myArray[1]='405adc92-cfad-4be6-9ad2-ca363eda4933'
So what Could I do to get rid ?
could you not just add the ' at the beginning of each string, rather than first add too many of them and afterwards remove the wrongly placed?
foreach($myArray as $key => &$value) {
$value = "'" . $value;
}
or (may be more readable as not by-reference)
foreach($myArray as $key => $value) {
$myArray[$key] = "'" . $value;
}
You can use rtrim - http://uk1.php.net/manual/en/function.rtrim.php to achieve. The generic syntax is:
<?php
$foo = 'my string\'';
$bar = rtrim($foo, '\'');
var_dump($foo); //shows my string'
var_dump($bar); //shows my string
so in your case take the array values, then use rtrim($myArray['myKey'], '\'') - this should do it for you :)
Related
I Want change all Strings starting with {" and ending with "} to a variable,
for example:
Hello {username}, -> to Hello $array['username']
Your Country is {country}, -> Your Country is $array['country']
But i get all strings text from database with one variable (Mysql) With $array['content']
What I Want:
str_replace("{$whatinhere}",$array['$copytohere'],$array['content']);
str_replace("{company}",$array['company'],$array['content']);
Use preg_replace_callback function
echo preg_replace_callback('~{(.+?)}~',
function($x) use ($array) { return isset($array[$x[1]]) ? $array[$x[1]] : ''; },
$array['content']);
I think you should try this...
$content = $array['content'];
$mainContent = str_replace('{username}', $array['username'], $content);
$mainContent = str_replace('{company}', $array['company'], $mainContent);
echo $mainContent;
As I understand the $array variable contains the placeholder key/value pairs and also the content. You can try following code for replacing all placeholder keys with their corresponding values:
foreach ($array as $key => $value) {
if ($key != "content") {
$array["content"] = str_replace("{" . $key . "}", $value, $array["content"]);
}
}
/** Print contents */
echo $array["content"];
How to extract values from string seperated by |
here is my string
$var='foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
i need to store
$foo=1478
$boo=7854
$ccc=74125
Of course every body would suggest the explode route:
$var = 'foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
foreach(array_filter(explode('|', $var)) as $e){
list($key, $value) = explode('=', $e);
${$key} = $value;
}
Also, another would be to convert pipes to ampersand, so that it can be interpreted with parse_str:
parse_str(str_replace('|', '&', $var), $data);
extract($data);
echo $foo;
Both would produce the same. I'd stay away with variable variables though, it choose to go with arrays.
Explode the string by | and you will get the different value as array which is separated by |. Now add the $ before each value and echo them to see what you want.
$var = 'foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$arr = explode("|", $var);
$arr = array_filter($arr);
foreach($arr as $val){
echo "$".$val."<br/>";
}
You will get:
$foo=1478
$boo=7854
$bar=74125
$aaa=74125
$bbb=470
$ccc=74125
$ddd=1200
OR if you want to store them in the $foo variable and show only the value then do this:
$var = 'foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$arr = explode("|", $var);
$arr = array_filter($arr);
foreach($arr as $val){
$sub = explode("=", $val);
$$sub[0] = $sub[1];
}
echo $foo; //1478
You can use PHP variable variable concept to achieve your objective:
Try this:
<?php
$var='foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$vars=explode("|",$var);
foreach($vars as $key=>$value){
if(!empty($value)){
$varcol=explode("=",$value);
$varname=$varcol[0];
$varvalue=$varcol[1];
$$varname=$varvalue; //In this line we use $$ i.e. variable variable concept
}
}
echo $foo;
I hope this works for you....
You can use explode for | with array_filter to remove blank elements from array, and pass the result to array_map with a reference array.
Inside callback you need to explode again for = and store that in ref array.
there after use extract to create variables.
$var='foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$result = array();
$x = array_map(function($arr) use(&$result) {
list($key, $value) = explode('=', $arr);
$result[$key] = $value;
return [$key => $value];
}, array_filter(explode('|', $var)));
extract($result);
Use explode function which can break your string.
$array = explode("|", $var);
print_r($array);
Trying to use the implode() function to add a string at the end of each element.
$array = array('9898549130', '9898549131', '9898549132');
$attUsers = implode("#txt.att.net,", $array);
print($attUsers);
Prints this:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132
How do I get implode() to also append the glue for the last element?
Expected output:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132#txt.att.net
//^^^^^^^^^^^^ See here
There is a simpler, better, more efficient way to achieve this using array_map and a lambda function:
$numbers = ['9898549130', '9898549131', '9898549132'];
$attUsers = implode(
',',
array_map(
function($number) {
return($number . '#txt.att.net');
},
$numbers
)
);
print_r($attUsers);
This seems to work, not sure its the best way to do it:
$array = array('9898549130', '9898549131', '9898549132');
$attUsers = implode("#txt.att.net,", $array) . "#txt.att.net";
print($attUsers);
Append an empty string to your array before imploding.
But then we have another problem, a trailing comma at the end.
So, remove it.
Input:
$array = array('9898549130', '9898549131', '9898549132', '');
$attUsers = implode("#txt.att.net,", $array);
$attUsers = rtrim($attUsers, ",")
Output:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132#txt.att.net
This was an answer from my friend that seemed to provide the simplest solution using a foreach.
$array = array ('1112223333', '4445556666', '7778889999');
// Loop over array and add "#att.com" to the end of the phone numbers
foreach ($array as $index => &$phone_number) {
$array[$index] = $phone_number . '#att.com';
}
// join array with a comma
$attusers = implode(',',$array);
print($attusers);
$result = '';
foreach($array as $a) {
$result = $result . $a . '#txt.att.net,';
}
$result = trim($result,',');
There is a simple solution to achieve this :
$i = 1;
$c = count($array);
foreach ($array as $key => $val) {
if ($i++ == $c) {
$array[$key] .= '#txt.att.net';
}
}
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 ;)
I have a string that contains elements from array.
$str = '[some][string]';
$array = array();
How can I get the value of $array['some']['string'] using $str?
This will work for any number of keys:
$keys = explode('][', substr($str, 1, -1));
$value = $array;
foreach($keys as $key)
$value = $value[$key];
echo $value
You can do so by using eval, don't know if your comfortable with it:
$array['some']['string'] = 'test';
$str = '[some][string]';
$code = sprintf('return $array%s;', str_replace(array('[',']'), array('[\'', '\']'), $str));
$value = eval($code);
echo $value; # test
However eval is not always the right tool because well, it shows most often that you have a design flaw when you need to use it.
Another example if you need to write access to the array item, you can do the following:
$array['some']['string'] = 'test';
$str = '[some][string]';
$path = explode('][', substr($str, 1, -1));
$value = &$array;
foreach($path as $segment)
{
$value = &$value[$segment];
}
echo $value;
$value = 'changed';
print_r($array);
This is actually the same principle as in Eric's answer but referencing the variable.
// trim the start and end brackets
$str = trim($str, '[]');
// explode the keys into an array
$keys = explode('][', $str);
// reference the array using the stored keys
$value = $array[$keys[0][$keys[1]];
I think regexp should do the trick better:
$array['some']['string'] = 'test';
$str = '[some][string]';
if (preg_match('/\[(?<key1>\w+)\]\[(?<key2>\w+)\]/', $str, $keys))
{
if (isset($array[$keys['key1']][$keys['key2']]))
echo $array[$keys['key1']][$keys['key2']]; // do what you need
}
But I would think twice before dealing with arrays your way :D