I want to merge two arrays and replace the text with strtr function.
I was using this before
$text = "cat cow";
$array = array(
"cat" => "dog",
"cow" => "bull"
);
$output = strtr($text, $array);
this returned dog bull...
Now I have two arrays like this...
$a = array("cat", "dog");
$b = array("dog", "bull");
Both the arrays will have values to replace
Now, how do I combine them and replace? I tried $array = $a + $b and array_combine, but they didn't work...
Please Help...
I think two arrays must be
$a = array("cat", "cow");
$b = array("dog", "bull");
And you can use
$c = array_combine($a, $b);
$output = strtr($text, $c);
I dont know how you have tried.
$text = "cat cow";
$array = array(
"cat" => "dog",
"cow" => "bull"
);
$text = "cat cow";
$array = array("cat" => "dog",
"cow" => "bull"
);
$output = strtr($array, $array);
echo $output;
//output -> dog bull
$a = array("cat", "cow");
$b = array("dog", "bull");
$c = array_combine($a,$b);
print_r($c);
$output1 = strtr($text, $c);
echo $output1;
//output -> dog bull
I thing the above code gives you what output you need.
I think you have used the wrong array
Check the $a and $b array
I hope i have helped you.
Do you mean merge them to get array('cat','dog','bull')? If so just do:
$array = array_unique(array_merge($a,$b));
Related
I have two arrays, $array_A and $array_B. I'd like to append the first value from $array_B to the end of the first value of $array_A and repeat this approach for all elements in both arrays.
$array_A = ['foo', 'bar', 'quuz'];
$array_B = ['baz', 'qux', 'corge'];
Expected output after squishing:
['foobaz', 'barqux', 'quuzcorge']
array_merge($array_A, $array_B) simply appends array B onto array A, and array_combine($array_A, $array_B) sets array A to be the key for array B, neither of which I want. array_map seems pretty close to what I want, but seems to always add a space between the two, which I don't want.
It would be ideal for the lengths of each array it to be irrelevant (e.g. array A has five entries, array B has seven entries, extra entries are ignored/trimmed) but not required.
// updated version
$a = ['a', 'b', 'c'];
$b = ['d', 'e', 'f', 'g'];
print_r(array_map('implode', array_map(null, $a, $b)));
Probably the fastest code, but more verbose than other options.
//updated version
$array_A = ['foo', 'bar', 'quuz'];
$array_B = ['baz', 'qux', 'corge'];
for ($i = 0, $c = count($array_A); $i<$c; $i++) {
$result[$i] = $array_A[$i].$array_B[$i];
}
var_dump($result);
There isn't an array function in PHP that does exactly that. However, you can write one yourself, like this one:
function array_zip($a1, $a2) {
$out = [];
for($i = 0; $i < min(sizeof($a1), sizeof($a2)); $i++) {
array_push($out, $a1[$i] . $a2[$i]);
}
return $out;
}
So given these arrays and running it:
$a = ["foo", "bar"];
$b = ["baz", "qux"];
print_r(array_zip($a, $b));
You would get:
Array
(
[0] => foobaz
[1] => barqux
)
Try this:
$A = ['foo', 'bar'];
$B = ['baz', 'qux'];
function arraySquish($array)
{
$new = [''];
foreach($array as $val) {
$new[0] .= $val;
}
return $new;
}
$A = arraySquish($A);
$B = arraySquish($B);
echo '<pre>';
print_r($A);
print_r($B);
echo '</pre>';
PHP Fiddle here.
An explicit array_map:
<?php
$colours = ['red', 'white', 'blue'];
$items = ['robin', 'cloud', 'mountain'];
$squished =
array_map(
function($colour, $item) {
return $colour.$item;
},
$colours,
$items
);
var_export($squished);
Output:
array (
0 => 'redrobin',
1 => 'whitecloud',
2 => 'bluemountain',
)
If you want to only go as far as the smallest array, you could either return null if either entries are null, and then filter your result.
Or truncate the arrays to the same length:
$b = array_intersect_key($b, $a);
$a = array_intersect_key($a, $b);
Regardless of if both arrays have the same length or if one is longer than the other or in what order the arrays occur in, the following technique will "squish" the values into a flat array of strings.
array_map() only needs to be called once and implode()'s default "glue" string is an empty string -- so it can be omitted.
Code: (Demo)
$a = ['a', 'b', 'c'];
$b = ['d', 'e', 'f', 'g'];
var_export(array_map(fn() => implode(func_get_args()), $a, $b));
Or consolidate the column data with spread operator: (Demo)
var_export(array_map(fn(...$column) => implode($column), $a, $b));
Output:
array (
0 => 'ad',
1 => 'be',
2 => 'cf',
3 => 'g',
)
First string:
$a = '_edit_last,_edit_lock,wpvp_fp_code,video_category';
second string:
$b = '1,1464965316:1,{"src":"http://localhost/wbg/wp-content/uploads/2016/05/PHP-Tutorial-1-Introduction-PHP-For-Beginners.mp4","splash":"http://localhost/wbg/wp-content/uploads/2016/05/default_image.jpg","width":"640","height":"360"},free 200';
Convert String into combined array.
I need out put for:
array("_edit_last"=>" 1", "_edit_lock"=>"1464965316:1", "wpvp_fp_code"=>"{"src":"http://localhost/wbg/wp-content/uploads/2016/05/PHP-Tutorial-1-Introduction-PHP-For-Beginners.mp4","splash":"http://localhost/wbg/wp-content/uploads/2016/05/default_image.jpg","width":"640","height":"360"}","video_category"=>"free 200");
Use array merges recursive function to merge two arrays
For example
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
Array Combine Function:
$a = array('_edit_last', '_edit_lock', 'wpvp_fp_code', 'video_category');
$b = array('1', '1464965316:1', '"{src":"http://localhost/wbg/wp-content/uploads/2016/05/PHP-Tutorial-1-Introduction-PHP-For-Beginners.mp4","splash":"http://localhost/wbg/wp-content/uploads/2016/05/default_image.jpg","width":"640","height":"360"}','free 200');
$c = array_combine($a, $b);
echo "<pre>";
print_r($c);
WATCH DEMO
Convert sting into array
$str = '_edit_last,_edit_lock,wpvp_fp_code,video_category';
print_r (explode(", ",$str));
DEMO
I have used the double space instead of a comma(,) in string2. Because comma(,) is not a unique function
DEMO - 3
Do you have an idea, how can a string be converted to a variable, e.g.
there is a string -> $string = 'one|two|three';
there is an array -> $arr = array('one' => array('two' => array('three' => 'WELCOME')));
I want to use all with explode(); exploded values to access the array $arr. I tried this code:
$c = explode('|', $string);
$str = 'arr[' . implode('][', $c) . ']';
echo $$str;
It doesnt work, sadly :( Any ideas?
You're doing it wrong.
You can do what you want with a loop to go through the array level by level
$string = 'one|two|three';
$arr = array('one' => array('two' => array('three' => 'WELCOME')));
$c = explode('|', $string);
$result = $arr;
foreach($c as $key)
$result = $result[$key];
echo $result; // WELCOME
Here's a sort of recursive function:
$ex_keys = array('one', 'two', 'three');
$ex_arr = array('one' => array('two' => array('three' => 'WELCOME')));
function get_recursive_var($keys, $arr) {
if (sizeof($keys) == 1)
return $arr[$keys[0]];
else {
$key = array_shift($keys);
return get_recursive_var($keys, $arr[$key]);
}
}
var_dump(get_recursive_var($ex_keys, $ex_arr));
//I have array like below:
$a =array('1,2,6');
$b =array('2,3,1');
//Then I using ArrayCombine :
$arr_combine = array_combine( $a, $b );
//OUTPUT:
//Array( [1,2,6] => 2,3,1 ) ;
how can I get array like below?
//OUTPUT:
array( 1=>2, 2=>3, 6=>1 );
If you have the array like that, then you have to explode the element.
$result = array_combine(explode(',', $a[0]), explode(',', $b[0]));
It's taking as complete one string due to your present quotes in arrays,
Should be,
$a = array('1','2','6'); // And not '1,2,6'
$b = array('2','3','1');
$arr_combine = array_combine( $a, $b );
DEMO.
And if you can't change the array & have the format like that only see #xdazz answer.
For your second question check like this
<?php
$x = array( 1 => '2', 2 => '3', 6 => '1') ;
$y = array( 1 => '2', 6 => '2' ) ;
$s = array();
foreach($x as $key=>$val)
{
if (array_key_exists($key,$y))
{
$s[$key] = $x[$key] + $y[$key];
}
}
var_dump($s);
?>
Try like this
<?php
$a =array('1,2,6');
$b =array('2,3,1');
$a = explode(',',$a[0]);
$b = explode(',',$b[0]);
var_dump($a);
var_dump($b);
var_dump(array_combine($a,$b));
?>
I've recently learned how to join 2 arrays using the + operator in PHP.
But consider this code...
$array = array('Item 1');
$array += array('Item 2');
var_dump($array);
Output is
array(1) { [0]=> string(6) "Item
1" }
Why does this not work? Skipping the shorthand and using $array = $array + array('Item 2') does not work either. Does it have something to do with the keys?
Both will have a key of 0, and that method of combining the arrays will collapse duplicates. Try using array_merge() instead.
$arr1 = array('foo'); // Same as array(0 => 'foo')
$arr2 = array('bar'); // Same as array(0 => 'bar')
// Will contain array('foo', 'bar');
$combined = array_merge($arr1, $arr2);
If the elements in your array used different keys, the + operator would be more appropriate.
$arr1 = array('one' => 'foo');
$arr2 = array('two' => 'bar');
// Will contain array('one' => 'foo', 'two' => 'bar');
$combined = $arr1 + $arr2;
Edit: Added a code snippet to clarify
Use array_merge()
See the documentation here:
http://php.net/manual/en/function.array-merge.php
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
IMO some of the previous answers are incorrect!
(It's possible to sort the answers to start from oldest to newest).
array_merge() actually merges the arrays, meaning, if the arrays have a common item one of the copies will be omitted. Same goes for + (union).
I didn't find a "work-around" for this issue, but to do it manually...
Here it goes:
<?php
$part1 = array(1,2,3);
echo "array 1 = \n";
print_r($part1);
$part2 = array(4,5,6);
echo "array 2 = \n";
print_r($part2);
$ans = NULL;
for ($i = 0; $i < count($part1); $i++) {
$ans[] = $part1[$i];
}
for ($i = 0; $i < count($part2); $i++) {
$ans[] = $part2[$i];
}
echo "after arrays concatenation:\n";
print_r($ans);
?>
use the splat ( or spread ) operator:
$animals = ['dog', 'cat', 'snake', 'pig', 'chicken'];
$fruits = ['apple', 'banana', 'water melon'];
$things = [...$animals, ...$fruits];
source: https://www.kindacode.com/article/merging-arrays-in-php-7/
+ is called the Union operator, which differs from a Concatenation operator (PHP doesn't have one for arrays). The description clearly says:
The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.
With the example:
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b;
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}
Since both your arrays have one entry with the key 0, the result is expected.
To concatenate, use array_merge.
Try array_merge.
$array1 = array('Item 1');
$array2 = array('Item 2');
$array3 = array_merge($array1, $array2);
I think its because you are not assigning a key to either, so they both have key of 0, and the + does not re-index, so its trying to over write it.
It is indeed a key conflict. When concatenating arrays, duplicate keys are not overwritten.
Instead you must use array_merge()
$array = array_merge(array('Item 1'), array('Item 2'));
$array = array('Item 1');
array_push($array,'Item 2');
or
$array[] = 'Item 2';
This works for non-associative arrays:
while(($item = array_shift($array2)) !== null && array_push($array1, $item));
Try saying
$array[] = array('Item 2');
Although it looks like you're trying to add an array into an array, thus $array[][] but that's not what your title suggests.
you may use operator .
$array3 = $array1.$array2;