I want to create separate variables from the key of an array where variable is the key and the content is the value of that key in the array
extract($array);
Example
<?php
$array = array('a' => 'abc', 'b' => 'def');
extract($array);
var_dump($a, $b);
// string(3) "abc"
// string(3) "def"
See it.
using this way
$data=array();
$data["value1"]=3;
$data["value2"]=4;
$three = $data["value1"];
$four = $data["value2"];
Use the extract() function for this.
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array);
which will give:
$color = 'blue'
$size = 'medium'
$shape = 'sphere'
use
extract($array);
PHP's extract function will do exactly that.
Related
I am trying to separate them all according to white space.
$string = "1 2 3 10 12";
According to this string, I want to separate like that.
$a = "1";
$b = "2";
$c = "3";
$d = "10";
$e = "12";
After that, I would like to check those strings are included as the key of an array. Here is my array,
$data = [
"1" => "Book",
"2" => "Paper",
"3" => "Pencil",
"10" => "Eraser",
"11" => "Ruler",
];
So, How can I separate an array and store the parts in each variable?
And How to check those variable are included in array as a key? Sorry for my English :D. Thanks.
Use the explode function to seperate the values and then check if the array key exists using array key exists.
$stringArray = explode(" ",$string);
foreach($stringArray as $stringPeice){
if(array_key_exists($stringPeice, $data)){
//do something
}
}
You can use explode to create an array of keys and then use array_diff to get an array of keys that are not in the $data:
$string = "1 2 3 10 12";
$keys = explode(' ', $string);
$data = [
"1" => "Book",
"2" => "Paper",
"3" => "Pencil",
"10" => "Eraser",
"11" => "Ruler",
];
$diff = array_diff($keys, array_keys($data));
Here is the demo.
If you want to get the entries from $data whose key exists in $string, you can use array_intersect_key(), and array_fill_keys() to create an array containing keys from the result of exploding $string:
$o = array_intersect_key($data, array_fill_keys(explode(" ", $string), ""));
Here's a demo
Following Below are two arrays which i wanna compare and remove the same values something like array_diff() Function and i want to store the result in third array
$array1 = Array([0] => Array([a] => XYZ,[b] => ABC))
$array2 = Array([0] => Array([a] => XYZ,[b] => ABC),[1] => Array([a] => PQR,[b] => XYZ))
$array3 = array_diff($array1,$array2);
//$array3 value must return this value Array([1] => Array[a]=> PQR,[b] => XYZ)
I don't know what i am doing wrong but i am getting error that array cannot be converted into string. Can anyone help me with this?
Thanks in advance
If you are sure that your $array2 will always contain more elements than $array1 then here is your solution:
$array1 = array(array('a' => 'XYZ','b' => 'ABC'));
$array2 = array(array('a' => 'XYZ','b' => 'ABC'),array('a' => 'PQR','b' => 'XYZ'));
$limit = count($array2);
$array3 = array();
for($i=0;$i<$limit;$i++){
if(empty($array1[$i]))
$array3[] = $array2[$i];
$array3[] = array_diff($array1[$i],$array2[$i]);
}
foreach($array3 as $k=>$a3){
if(empty($a3)||($a3===NULL))
continue;
$result[$k] = $a3;
}
var_dump($result); //array(1) { [1]=> array(2) { ["a"]=> string(3) "PQR" ["b"]=> string(3) "XYZ" } }
Please note that array_diff works on 1D array and you was providing 2D arrays as parameter and that's why it wasn't working.
Also your way of defining $array1 and $array2 is wrong, please check this solution for right syntax.
I hope it helps
I have two associative array.
$Array1 = array(
'abc'=> 'abc',
'def'=> 'def'
);
$Array2 = array(
'123'=> '123',
'456'=> '456'
);
I am merging them using array_merge.
$Array3 = array_merge($Array1, $Array2);
Now value of $Array3 is like this.
Array
(
[abc] => abc
[def] => def
[0] => 123
[1] => 456
)
It looks really odd until I read php manual which says Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array. array_merge manual
My questing How can I merge both array without loosing their associative keys.
Both array can have common KEYS and I don't want to loose my information also. :(
By +:
$Array1 = array(
'abc'=> 'abc',
'def'=> 'def'
);
$Array2 = array(
'123'=> '123',
'456'=> '456'
);
var_dump($Array1 + $Array2);
This will preserve the index, but note this will not overwrite the value of the first array if same key exists in first array.
And if you want the overwrite working, then there is array_replace function for this:
var_dump(array_replace($Array1, $Array2));
Try this code :) it will work
function my_merge($array1,$array2)
{
foreach($array2 as $key => $value)
{
$array1[$key] = $value;
}
return $array1;
}
$Array1 = array(
'abc'=> 'abc',
'def'=> 'def'
);
$Array2 = array(
'123'=> '123',
'456'=> '456'
);
$Array3 = my_merge($Array1, $Array2);
For associative arrays, use
$result = $Array1 + $Array2;
-but note, that for numeric keys this will also re-index:
$Array1 = array(
'abc',
'def'=> 'def'
);
$Array2 = array(
'123',
'456'
);
var_dump($Array1 + $Array2);
//array(3) { [0]=> string(3) "abc" ["def"]=> string(3) "def" [1]=> string(3) "456" }
If you have same keys in your arrays, you can use:
$result = array_reduce(array_keys($Array1), function($c, $x) use ($Array1)
{
$c[$x] = isset($c[$x])
?array_merge((array)$c[$x], [$Array1[$x]])
:$Array1[$x];
return $c;
}, $Array2);
In PHP I create an array of key value pairs like this, how to I get "mykey"?
$arr = array("mykey"=>"myvalue");
I know the code below will work, but I am interested to know if there is a language construct in PHP that allows me to this in a easier fashion.
foreach($arr as $key=>$value){
$result = $key;
break;
}
echo $result;
Just Use key if you dealing with one element and array_keys with arrays with multiple values.
Example
$arr = array("mykey"=>"myvalue");
var_dump(key($arr));
Or
var_dump(array_keys($arr));
Output
string 'mykey' (length=5)
and
array
0 => string 'mykey' (length=5)
try this
you can use array_keys function in php
<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
?>
you need to use array_keys, here's the manual
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;