Convert PHP string to custom formatted array for function - php

I need help converting a PHP string into an array that is formatted to work within a PHP function. I have a string like this:
$string = '11111, 22222, 33333';
I need this string to explode into an array that looks like this:
array("11111"=>"11111","22222"=>"22222","33333"=>"33333")';
The function looks like this:
function callback_numbers() {
$numbers = array(
"11111"=>"11111",
"22222"=>"22222",
"33333"=>"33333",
);
return $numbers;
}
I can't get the array to appear correctly when inside the function so that the array is returned correctly and the function works. When I print_t $numbers it looks ok but it won't work when I return $numbers.

Try this. Yoy can split using , but after you need to trim as there might be spaces between your numbers
$string = '11111, 22222, 33333';
$numbers = explode(',', $string );
$result = [];
foreach ($numbers as $item) {
$item = trim( $item );
$result [ $item ] = $item;
}
var_dump($result);

Related

How to convert String Array to php Array?

How to convert Sting Array to PHP Array?
"['a'=>'value one','key2'=>'value two']"
to
$data=['a'=>'value one','key2'=>'value two'];
Please let me know if anyone knows of any solution
I want to take array input via textarea. And I want to convert that to a PHP array.
When I'm through textarea
['a'=>'value one','key2'=>'value two']
This is happening after submitting the from
"['a'=>'value one','key2'=>'value two']"
Now how do I convert from this to PHP Array?
Assuming you are not allowing multi dimensional arrays, this will work:
$stringArray = "['a'=>'value one','key2'=>'value two']";
$array = array();
$trimmedStringArray = trim( $stringArray, '[]' );
$splitStringArray = explode( ',', $trimmedStringArray );
foreach( $splitStringArray as $nameValuePair ){
list( $key, $value ) = explode( '=>', $nameValuePair );
$array[$key] = $value;
}
Output:
Array
(
['a'] => 'value one'
['key2'] => 'value two'
)
You will probably want to do some error checking to make sure the input is in the correct format before you process the input.
Extremely unsafe version using eval():
<?php
$a = "['a'=>'value one','key2'=>'value two']";
eval('$b = '.$a.';');
print('<pre>');
print_r($b);
Use only when you are sure, that other people can't use your textarea input!
Using replacements to convert this to json is a much better option for public forms. Additionally, if you use this at your work, you probably would get fired :)
With syntax error catch:
<?php
$a = "['a'=>'value one','key2'=>'value two'dsbfbtrg]";
try {
eval('$b = '.$a.';');
} catch (ParseError $e) {
print('Bad syntax');
die();
// or do something about the error
}
print('<pre>');
print_r($b);
Another option:
<?php
$string = "['a'=>'value one','key2'=>'value two']";
$find = ["'", "=>", "[", "]"];
$replace = ["\"", ":", "{", "}"];
$string = str_replace($find, $replace, $string);
$array = json_decode($string, true);
var_dump($array);
?>

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

preg_replace() digits to an array item

I've got this array:
<?php
$menu = array(
9 => 'pages/contact/',
10 => 'pages/calender/jan/'
//...
);
?>
And I've got a string that looks like this:
$string = "This is a text with a link inside it.";
I want to replace ###9### with pages/contact/.
I've got this:
$string = preg_replace("/###[0-9]+###/", "???", $string);
But I can't use $menu[\\\1]. Any help is appreciated.
There is a solution with preg_replace_callback but you can build an array where searched strings are associated to their replacement strings and then use strtr:
$menu = array(
9 => 'pages/contact/',
10 => 'pages/calender/jan/'
.... );
$keys = array_map(function ($i) { return "###$i###"; }, array_keys($menu));
$rep = array_combine($keys, $menu);
$result = strtr($string, $rep);
For this you need preg_replace_callback(), where you can apply a callback function fore each match, e.g.
$string = preg_replace_callback("/###(\d+)###/", function($m)use($menu){
if(isset($menu[$m[1]]))
return $menu[$m[1]];
return "default";
}, $string);

PHP : foreach warning

I'am executing code :
<?php
$input="ABC123";
$splits = chunk_split($input,2,"");
foreach($splits as $split)
{
$split = strrev($split);
$input = $input . $split;
}
?>
And output that i want is :
BA1C32
But it gaves me Warning.
Warning: Invalid argument supplied for foreach() in /home/WOOOOOOOOHOOOOOOOO/domains/badhamburgers.com/public_html/index.php on line 4
chunk_split doesn't return an array but rather a part of the string.
You should use str_split instead:
$input="ABC123";
$splits = str_split($input, 2);
And don't forget to reset your $input before the loop, else it will contain the old data aswell.
It looks like http://php.net/manual/en/function.chunk-split.php returns a string, not an array. You could use str_split instead:
$input = "ABC123";
$splits = str_split( $input, 2 );
$output = "";
foreach( $splits as $split ){
$split = strrev($split);
$output .= $split;
}
As the documentation for chunk_split mentions clearly, http://php.net/manual/en/function.chunk-split.php chunk split returns a string.
foreach expects an array as first argument.

Replace string in an array with PHP

How can I replace a sub string with some other string for all items of an array in PHP?
I don't want to use a loop to do it. Is there a predefined function in PHP that does exactly that?
How can I do that on keys of array?
Why not just use str_replace without a loop?
$array = array('foobar', 'foobaz');
$out = str_replace('foo', 'hello', $array);
$array = array_map(
function($str) {
return str_replace('foo', 'bar', $str);
},
$array
);
But array_map is just a hidden loop. Why not use a real one?
foreach ($array as &$str) {
$str = str_replace('foo', 'bar', $str);
}
That's much easier.
This is a very good idea that I found and used successfully:
function str_replace_json($search, $replace, $subject)
{
return json_decode(str_replace($search, $replace, json_encode($subject)), true);
}
It is good also for multidimensional arrays.
If you change the "true" to "false" then it will return an object instead of an associative array.
Source: Codelinks
I am not sure how efficient this is, but I wanted to replace strings in a big multidimensional array and did not want to loop through all items as the array structure is pretty dynamic.
I first json_encode the array into a string.
Replace all the strings I want (need to use preg_replace if there are non-English characters that get encoded by json_encode).
json_decode to get the array back.
function my_replace_array($array,$key,$val){
for($i=0;$i<count($array);$i++){
if(is_array($array[$i])){
$array[$i] = my_replace_array($array[$i],$key,$val);
}else{
$array[$i]=str_replace($key,$val,$array[$i]);
}
}
return $array;
}
With array_walk_recursive()
function replace_array_recursive( string $needle, string $replace, array &$haystack ){
array_walk_recursive($haystack,
function (&$item, $key, $data){
$item = str_replace( $data['needle'], $data['replace'], $item );
return $item;
},
[ 'needle' => $needle, 'replace' => $replace ]
);
}
$base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));
$basket = array_replace_recursive($base, $replacements);
$basket = array_replace($base, $replacements);

Categories