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

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

Related

replace all keys in php array

This is my array:
['apple']['some code']
['beta']['other code']
['cat']['other code 2 ']
how can I replace all the "e" letters with "!" in the key name and keep the values
so that I will get something like that
['appl!']['some code']
['b!ta']['other code']
['cat']['other code 2 ']
I found this but because I don't have the same name for all keys I can't use It
$tags = array_map(function($tag) {
return array(
'name' => $tag['name'],
'value' => $tag['url']
);
}, $tags);
I hope your array looks like this:-
Array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
If yes then you can do it like below:-
$next_array = array();
foreach ($array as $key=>$val){
$next_array[str_replace('e','!',$key)] = $val;
}
echo "<pre/>";print_r($next_array);
output:- https://eval.in/780144
You can stick with array_map actually. It is not really practical, but as a prove of concept, this can be done like this:
$array = array_combine(
array_map(function ($key) {
return str_replace('e', '!', $key);
}, array_keys($array)),
$array
);
We use array_keys function to extract keys and feed them to array_map. Then we use array_combine to put keys back to place.
Here is working demo.
Here we are using array_walk and through out the iteration we are replacing e to ! in key and putting the key and value in a new array.
Try this code snippet here
<?php
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
$result=array();
array_walk($firstArray, function($value,$key) use (&$result) {
$result[str_replace("e", "!", $key)]=$value;
});
print_r($result);
If you got this :
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
You can try this :
$keys = array_keys($firstArray);
$outputArray = array();
$length = count($firstArray);
for($i = 0; $i < $length; $i++)
{
$key = str_replace("e", "!", $keys[ $i ]);
$outputArray[ $key ] = $firstArray[$keys[$i]];
}
We can iterate the array and mark all problematic keys to be changed. Check for the value whether it is string and if so, make sure the replacement is done if needed. If it is an array instead of a string, then call the function recursively for the inner array. When the values are resolved, do the key replacements and remove the bad keys. In your case pass "e" for $old and "!" for $new. (untested)
function replaceKeyValue(&$arr, $old, $new) {
$itemsToRemove = array();
$itemsToAdd = array();
foreach($arr as $key => $value) {
if (strpos($key, $old) !== false) {
$itemsToRemove[]=$key;
$itemsToAdd[]=str_replace($old,$new,$key);
}
if (is_string($value)) {
if (strpos($value, $old) !== false) {
$arr[$key] = str_replace($old, $new, $value);
}
} else if (is_array($value)) {
$arr[$key] = replaceKeyValue($arr[$key], $old, $new);
}
}
for ($index = 0; $index < count($itemsToRemove); $index++) {
$arr[$itemsToAdd[$index]] = $itemsToRemove[$index];
unset($arr[$itemsToRemove[$index]]);
}
return $arr;
}
Another option using just 2 lines of code:
Given:
$array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
Do:
$replacedKeys = str_replace('e', '!', array_keys($array));
return array_combine($replacedKeys, $array);
Explanation:
str_replace can take an array and perform the replace on each entry. So..
array_keys will pull out the keys (https://www.php.net/manual/en/function.array-keys.php)
str_replace will perform the replacements (https://www.php.net/manual/en/function.str-replace.php)
array_combine will rebuild the array using the keys from the newly updated keys with the values from the original array (https://www.php.net/manual/en/function.array-combine.php)

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

Convert array of delimited strings to variables

I need to convert all items in array to variables like:
$item[0] = "apple=5";
$item[1] = "banana=7";
$item[2] = "orange=8";
And I want to convert it to this:
$apple = 5;
$banana = 7;
$orange = 8;
Like normal variables. Is it possible?
Seems like a silly thing to do, why not convert it into an associative array? But if you must:
foreach($item as $x) {
list($name, $val) = explode('=', $x, 2);
$$name = $val;
}
You can try to join the array and parse the string into variables
parse_str(implode('&',$item));
You can do it like this
$item[0] = "apple=5";
$item[1] = "banana=7";
$item[2] = "orange=8";
foreach($item as $row)
{
$new = explode('=',$row);
$array[$new[0]] = $new[1];
}
extract($array);
echo $apple;
echo $banana;
echo $orange;
Your array looks like someone exploded an ini file on its newlines.
Implode with newlines, then parse, then call extract() to generate the variables. (Demo)
extract(
parse_ini_string(
implode(PHP_EOL, $item)
)
);
echo "$apple $banana $orange";
Using explode() or parse_ini_string() or preg_ functions (etc.) will render the numeric values as string-type.
If you'd like the numeric values to be integer-typed, then using %d in the "format" parameter of sscanf() will be most direct. (Demo1)
foreach ($item as $string) {
[$key, $$key] = sscanf($string, '%[^=]=%d');
}
Generally speaking, I do not advise the generation of individual variable (I more strenuously advise against variable variables). Perhaps an associative array would be suitable. (Demo)
$result = [];
foreach ($item as $string) {
[$key, $result[$key]] = sscanf($string, '%[^=]=%d');
}
var_dump($result);

How to use Explode in my case?

I have a variable that contains text with values according to an example below:
$data = "5:7|4:1|504:2|1:3|"
And I would like to achieve results like this:
$data[5] = 7;
$data[4] = 1;
$data[504] = 2;
$data[1] = 3;
I tried with explode:
$data = explode("|", $data);
//but it makes $data[0]="5:7"; $data[1]="4:1"; and so on.
Should I use explode again? Is it has any sense, or is there another way? I would like to ask for a hint or help.
There may be a more clever way, but I'd do it like this:
$data = array();
foreach (explode("|", $your_data) as $part)
{
$pieces = explode(':', $part);
// Assumes we have 2 pieces, might want to make sure here...
$data[$pieces[0]] = $pieces[1];
}
Also, I'm not sure what this data represents but keep in mind that array keys will overwrite each other, so 1:1|1:2 will result in an array with only one item (the last piece). There may be good reason to take another approach.
Sure, explode again:
$data = "5:7|4:1|504:2|1:3";
$array = array();
foreach (explode('|', $data) as $pair) {
list($id, $val) = explode(':', $pair);
$array[$id] = $val;
}
Yes you should use explode twice, like this
$newData = array();
$pairs = explode('|',$data);
foreach($pairs as $pair){
$tmp = explode(':',$pair);
$newData[$tmp[0]] = $tmp[1];
}
Try using a regexp:
$data = preg_split ("\||:", $data);
One line version:
$data = array_map(function($d) { return (int)explode(":", $d)[1]; }, explode("|", $data));

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