This question already has answers here:
Create an assoc array with equal keys and values from a regular array
(3 answers)
Closed 6 years ago.
I have this array:
$a = array('b', 'c', 'd');
Is there a simple method to convert the array to the following?
$a = array('b' => 'b', 'c' => 'c', 'd' => 'd');
$final_array = array_combine($a, $a);
Reference: http://php.net/array-combine
P.S. Be careful with source array containing duplicated keys like the following:
$a = ['one','two','one'];
Note the duplicated one element.
Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.
I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
So I solved it like this:
foreach($array as $key => $val) {
$new_array[$val]=$val;
}
Related
This question already has answers here:
PHP - Merging two arrays into one array (also Remove Duplicates)
(9 answers)
Closed 3 years ago.
I have two arrays one is the superset of other,how to create a third array which has all the values of both arryas but not repeating
me please
$a = array(1,2,3);
$b = array(1,2,3,4);
output must be like this
$c = array(1,2,3,4);
use array_merge() along with array_unique()
array_unique(array_merge($a,$b));
Output:-https://3v4l.org/lfm1b
Note:- if you want to re-index array use array_values() [added in my working example link]
Reference:
array_values()
$c = array_unique(array_merge($a, $b));
All of this can be seen in: http://php.net/manual/en/function.array-merge.php
Use array_merge with array_unique
print_r(array_unique(array_merge($a,$b)))
Use + sign to merge them
$c = $a + $b;
Working example :- https://3v4l.org/5P2LP
This question already has answers here:
Merge two arrays as key value pairs in PHP
(3 answers)
Closed 9 months ago.
Is it possible that I can get the data from the other array based on the value from another?
If I input value from array it will return a value from other array.
Example:
$arr1 = ['A','B','C'];
$arr2 = [1,2,3,];
Input: 2
Result: B
Do they need to be separate?
You could use array_combine() to assign a key to the value and then input is just $array[$input] - e.g.
$arr1 = ['A', 'B', 'C'];
$arr2 = [1, 2, 3];
$arr = array_combine($arr2, $arr1);
echo $arr[$_POST['input']]; # will display 2
Since your arrays have not been given any specific keys, they are assigned numerically indexes from PHP, starting from zero.
You can then use array_search() to get the key of the $arr2 array, and use that to find the value in $arr1.
$key = array_search($input, $arr2);
$output = $arr1[$key];
If either array has defined indexes, you can use array_values() to just get the values and get the numeric indexes from PHP again.
Live demo at https://3v4l.org/mf688
This function combine 2 or more arrays
<?php
$array1 = array('A', 'B', 'C');
$array2 = array('1', '2', '3');
$result = array_merge($array1, $array2);
print_r($result);
?>
Working with array $result above (1 of 2 possibility)
<?php echo $result[1]; ?>
Or use
<?php
$q = '2'; $key = array_search($q, $result);
if(!$key)
echo "This search returned no key and value pair";
else
echo "This search for value: " . $q . " is present in key: " . $key;
?>
This question already has answers here:
php array difference
(7 answers)
Closed 7 years ago.
I dispose of two arrays with the following contents:
$arr1 = "one", "two", "three";
$arr2 = "one", "two";
I want to make sure to return an array containing only the value "three";
In my applications in fact the values of $arr1 represent the link to be included in a table, those of $arr2 links already entered.
I tried using the function intersect but this returns the values that are duplicates, but I want to discard the duplicates and take only the values that are not present in $arr2;
$c = array_intersect($arr1, $arr2);
$filter= array_diff($arr1 , $arr2 );
This question already has answers here:
How to reindex an array?
(6 answers)
Closed 1 year ago.
I've encoded an Array I've made using the inbuilt json_encode(); function. I need it in the format of an Array of Arrays like so:
[["Afghanistan",32,12],["Albania",32,12]]
However, it is returning as:
{"2":["Afghanistan",32,12],"4":["Albania",32,12]}
How can I remove these row numbers without using any Regex trickery?
If the array keys in your PHP array are not consecutive numbers, json_encode() must make the other construct an object since JavaScript arrays are always consecutively numerically indexed.
Use array_values() on the outer structure in PHP to discard the original array keys and replace them with zero-based consecutive numbering:
Example:
// Non-consecutive 3number keys are OK for PHP
// but not for a JavaScript array
$array = array(
2 => array("Afghanistan", 32, 13),
4 => array("Albania", 32, 12)
);
// array_values() removes the original keys and replaces
// with plain consecutive numbers
$out = array_values($array);
json_encode($out);
// [["Afghanistan", 32, 13], ["Albania", 32, 12]]
json_encode() function will help you to encode array to JSON in php.
if you will use just json_encode function directly without any specific option, it will return an array.
Like mention above question
$array = array(
2 => array("Afghanistan",32,13),
4 => array("Albania",32,12)
);
$out = array_values($array);
json_encode($out);
// [["Afghanistan",32,13],["Albania",32,12]]
Since you are trying to convert Array to JSON, Then I would suggest to use JSON_FORCE_OBJECT as additional option(parameters) in json_encode, Like below
<?php
$array=['apple','orange','banana','strawberry'];
echo json_encode($array, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"}
?>
I want to add to Michael Berkowski's answer that this can also happen if the array's order is reversed, in which case it's a bit trickier to observe the issue, because in the json object, the order will be ordered ascending.
For example:
[
3 => 'a',
2 => 'b',
1 => 'c',
0 => 'd'
]
Will return:
{
0: 'd',
1: 'c',
2: 'b',
3: 'a'
}
So the solution in this case, is to use array_reverse before encoding it to json
I had a problem with accented characters when converting a PHP array to JSON. I put UTF-8 stuff all over the place but nothing solved my problem until I added this piece of code in my PHP while loop where I was pushing the array:
$es_words[] = array(utf8_encode("$word"),"$alpha","$audio");
It was only the '$word' variable that was giving a problem. Afterwards it did a jason_encode no problem.
Hope that helps
Is it possible to prepend an associative array with literal key=>value pairs? I know that array_unshift() works with numerical keys, but I'm hoping for something that will work with literal keys.
As an example I'd like to do the following:
$array1 = array('fruit3'=>'apple', 'fruit4'=>'orange');
$array2 = array('fruit1'=>'cherry', 'fruit2'=>'blueberry');
// prepend magic
$resulting_array = ('fruit1'=>'cherry',
'fruit2'=>'blueberry',
'fruit3'=>'apple',
'fruit4'=>'orange');
Can't you just do:
$resulting_array = $array2 + $array1;
?
You cannot directly prepend an associative array with a key-value pair.
However, you can create a new array that contains the new key-value pair at the beginning of the array with the union operator +. The outcome is an entirely new array though and creating the new array has O(n) complexity.
The syntax is below.
$new_array = array('new_key' => 'value') + $original_array;
Note: Do not use array_merge(). array_merge() overwrites keys and does not preserve numeric keys.
In your situation, you want to use array_merge():
array_merge(array('fruit1'=>'cherry', 'fruit2'=>'blueberry'), array('fruit3'=>'apple', 'fruit4'=>'orange'));
To prepend a single value, for an associative array, instead of array_unshift(), again use array_merge():
array_merge(array($key => $value), $myarray);
Using the same method as #mvpetrovich, you can use the shorthand version of an array to shorten the syntax.
$_array = array_merge(["key1" => "key_value"], $_old_array);
References:
PHP: array_merge()
PHP: Arrays - Manual
As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].
#Cletus is spot on. Just to add, if the ordering of the elements in the input arrays are ambiguous, and you need the final array to be sorted, you might want to ksort:
$resulting_array = $array1 + $array2;
ksort($resulting_array);
If using Laravel, you can use prepend on a collection instance
collect(['b' => 'b', 'c' => 'c'])->prepend('a','a');
// ['a'=>'a', 'b' => 'b', 'c' => 'c']
https://laravel.com/docs/9.x/collections#method-prepend