Merge an array with a string variable in PHP implode - php

implode(',', $a);
I want to attach the $q variable in front of the $a so like this
implode(',', $q.$a);
But that doesn`t work. How can i put 2 variables in a implode function?
$a is an array with domain names like "com, org" and $q is the text (string) you type in before the domain names will appear.
I get the following error:
invalid argument passed in line..
Whole code:
$a = ['nl','net','com','co'];
$q = $_REQUEST["q"];
$domain = explode(".", $q);
$ext = #$domain[1] ?: ' ';
if (empty($ext)) {
echo implode(',',$a);
} else if (in_array($ext, $a)) {
echo $q;
} else {
$r = [];
foreach ($a as $x) {
if (strstr($x, $ext)) {
$r[] = $x;
}
}
echo (count($r)) ? implode(',',$r) : implode(',',$a);
}

If $a is an array and $q is the prefix string you can achieve that with 2 steps:
Add the prefix with:
$a = array("com", "co");
$q = "robot.";
foreach ($a as &$value)
$value = $q.$value;
Second, use the implode:
echo implode(',',$a);
output is:
robot.com,robot.co
Edited
I think this will be more suitable for you:
$a = array("com", "co", "org");
$q = "robot.c";
$arr = explode(".", $q);
$output = array();
foreach ($a as &$value) {
if (substr($value, 0, strlen($arr[1])) === $arr[1])
$output[]= $arr[0] . "." . $value;
}
echo implode(',',$output);
In this code you take the domain prefix and search for all domain name that may be fit for the prefix.
Notice that is this example we have domain org but he does not show up because your prefix is c

You need to add your $q before implode function. You can add your $q into your $a array using array_map function.
$array = array('com', 'org', 'net');
$q = 'test';
$array = array_map(function($value) {
$q= "test"; // you $q value goes here.
return $q.".".$value;
}, $array);
echo implode(',',$array);

Assuming that your business logic guarantees that $a is never empty, then here is the most direct, efficient, and concise technique...
Code: (Demo)
$a = ['nl', 'net', 'com', 'co'];
$q = 'example';
echo "$q." . implode(",$q.", $a);
Output:
example.nl,example.net,example.com,example.co
See how there is no need to loop or call any additional functions?
This basic technique of expanding the delimiting glue can be seen in other usages like:
echo '<tr><td>' . implode('</td><td>', $array) . '</td></tr>';
The idea is that you prepend what you need before the first value, then you declare the glue to be the characters that you need to occur after each value AND before the next value.

Merge an array with a string variable in PHP with the help of implode function
$a = array("com", "co");
$q = "robot.c";
$temp = explode(".",$q);
foreach ($a as $value)
echo $value = $temp[0].".".$value;

Related

implode() string, but also append the glue at the end

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';
}
}

array values to nested array with PHP

I'm trying to figure out how I can use the values an indexed array as path for another array. I'm exploding a string to an array, and based on all values in that array I'm looking for a value in another array.
Example:
$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my#string#is#nested';
$items = explode('#', $var);
// .. echo $haystack[... items..?]
The number of values may differ, so it's not an option to do just $haystack[$items[0][$items[1][$items[2][$items[3]].
Any suggestions?
You can use a loop -
$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my#string#is#nested';
$items = explode('#', $var);
$temp = $haystack;
foreach($items as $v) {
$temp = $temp[$v]; // Store the current array value
}
echo $temp;
DEMO
You can use a loop to grab each subsequent nested array. I.e:
$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my#string#is#nested';
$items = explode('#', $var);
$val = $haystack;
foreach($items as $key){
$val = $val[$key];
}
echo $val;
Note that this does no checking, you likely want to check that $val[$key] exists.
Example here: http://codepad.org/5ei9xS91
Or you can use a recursive function:
function extractValue($array, $keys)
{
return empty($keys) ? $array : extractValue($array[array_shift($keys)], $keys) ;
}
$haystack = array('my' => array('string' => array('is' => array('nested' => 'hello'))));
echo extractValue($haystack, explode('#', 'my#string#is#nested'));

PHP Separate comma array into variable / values

I have a string in a table field that looks like this:
part1=1,part2=S,part3=Y,part4=200000
To call it from the table I do this:
while($row = mysqli_fetch_array($result)) {
$row['mystring'];
}
My problem is that I need to separate the parts into variables for example:
From this:
part1=1,part2=S,part3=Y,someothername=200000
To This:
$part1 = '1';
$part2 = 'S';
$part3 = 'Y';
$someothername = '200000';
How can I do this?
Use like this
parse_str( str_replace(",", "&", "part1=1,part2=S,part3=Y,someothername=200000") );
Use with there name like:
$part1 // return 1
$part2 // return S
$part3 // return Y
works like you want, see the demo
First split string:
$s = "part1=1,part2=S,part3=Y,part4=200000";
$a = explode(",",$s);
then foreach part of string ("part1=1"...) create an array and explode as variable:
foreach($a as $k=>$v)
{
$tmp = explode("=",$v);
$tmp = array($tmp[0]=>$tmp[1]);
extract($tmp);
}
echo $part1;
If you use PHP 5.3+ you can use array_map
<?php
$string = 'part1=1,part2=S,part3=Y,part4=200000';
array_map(function($a){
$tmp = explode('=', $a, 2);
global ${$tmp[0]}; //make vars available outside of this function scope
${$tmp[0]} = $tmp[1];
}, explode(',', $string));
//Variables available outside of array_map scope
echo $part1 . '<br>';
echo $part2 . '<br>';
echo $part3 . '<br>';
echo $part4 . '<br>';
?>
Double explode your string to get the wanted field :
$string ="part1=1,part2=S,part3=Y,someothername=200000";
foreach (explode(',', $string) as $parts) {
$part = explode('=', $parts);
$array[$part[0]] = $part[1];
}
var_dump($array);
Output :
array(4) {
["part1"]=>
string(1) "1"
["part2"]=>
string(1) "S"
["part3"]=>
string(1) "Y"
["someothername"]=>
string(6) "200000"
}
I wouldn't suggest the use of variable variables to get the output as :
$part1 = ...
$part2 = ...
Using an array is probably the easier and safest way to do here. As suggested in my comment, it avoid potential conflicts with variable names.
You can use something called 'Variable variables'. You can declare the content of a variable as a variable, if you use double dollar sign, instead of a single one. For example:
$fruit = "apple";
$$fruit = "this is the apple variable";
echo $apple;
It would output the following:
this is the apple variable
You have to be a bit more tricky with defining variables from an array, as you'd have to enclode the original variable in curly brackets. (for example: ${$fruit[0]})
So the answer to your question is:
$parts = "part1=1,part2=S,part3=Y,someothername=200000";
$parts_array = explode(",", $parts);
foreach ($parts_array as $value) {
$temp = explode("=", $value);
${$temp[0]} = $temp[1];
}
echo "$part1, $part2, $part3, $someothername";
PHPFiddle link: http://phpfiddle.org/main/code/adyb-ug5n

Convert delimited string into array key path and assign value

I have a string like this:
$string = 'one/two/three/four';
which I turn it into a array:
$keys = explode('/', $string);
This array can have any number of elements, like 1, 2, 5 etc.
How can I assign a certain value to a multidimensional array, but use the $keys I created above to identify the position where to insert?
Like:
$arr['one']['two']['three']['four'] = 'value';
Sorry if the question is confusing, but I don't know how to explain it better
This is kind of non-trivial because you want to nest, but it should go something like:
function insert_using_keys($arr, $keys, $value){
// we're modifying a copy of $arr, but here
// we obtain a reference to it. we move the
// reference in order to set the values.
$a = &$arr;
while( count($keys) > 0 ){
// get next first key
$k = array_shift($keys);
// if $a isn't an array already, make it one
if(!is_array($a)){
$a = array();
}
// move the reference deeper
$a = &$a[$k];
}
$a = $value;
// return a copy of $arr with the value set
return $arr;
}
$string = 'one/two/three/four';
$keys = explode('/', $string);
$arr = array(); // some big array with lots of dimensions
$ref = &$arr;
while ($key = array_shift($keys)) {
$ref = &$ref[$key];
}
$ref = 'value';
What this is doing:
Using a variable, $ref, to keep track of a reference to the current dimension of $arr.
Looping through $keys one at a time, referencing the $key element of the current reference.
Setting the value to the final reference.
You'll need to first make sure the key's exist, then assign the value. Something like this should work (untested):
function addValueByNestedKey(&$array, $keys, $value) {
$branch = &$array;
$key = array_shift($keys);
// add keys, maintaining reference to latest branch:
while(count($keys)) {
$key = array_pop($keys);
if(!array_key_exists($key, $branch) {
$branch[$key] = array();
}
$branch = &$branch[$key];
}
$branch[$key] = $value;
}
// usage:
$arr = array();
$keys = explode('/', 'one/two/three/four');
addValueByNestedKey($arr, $keys, 'value');
it's corny but:
function setValueByArrayKeys($array_keys, &$multi, $value) {
$m = &$multi
foreach ($array_keys as $k){
$m = &$m[$k];
}
$m = $value;
}
$arr['one']['two']['three']['four'] = 'value';
$string = 'one/two/three/four';
$ExpCheck = explode("/", $string);
$CheckVal = $arr;
foreach($ExpCheck AS $eVal){
$CheckVal = $CheckVal[$eVal]??false;
if (!$CheckVal)
break;
}
if ($CheckVal) {
$val =$CheckVal;
}
this will give u your value in array.

php call array from string

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

Categories