I have this array:
$arrayAll = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
where the keys are unique - they don't ever repeat. And the value could be either 1 or 2 - nothing else.
And I need to "split" this $arrayAll array into $array1 - that will contain everything with value 1 and $array2 - that will contain everything with value 2 so in the end I will have:
$array1 = [
'156' => '1',
'157' => '1',
'159' => '1',
'161' => '1'
];
and
$array2 = [
'158' => '2',
'160' => '2'
];
and as you can see, I will have the keys from the original array will remain the same.
What is the simplest thing to do to separate the original array like this?
This is probably the simplest way.
Loop it and create a temporary array to hold the values then extract the values to your array 1 and 2.
Foreach($arrayAll as $k => $v){
$res["array" . $v][$k] = $v;
}
Extract($res);
Var_dump($array1, $array2);
https://3v4l.org/6en6l
Updated to use extract and a method of variable variables.
The update means it will work even if there is a value "3" in the input array.
https://3v4l.org/jbvBf
Use foreach and compare each value and assign it to a new array.
$array1 = [];
$array2 = [];
foreach($arrayAll as $key=>$val){
if($val == 2){
$array2[$key] = $val;
}else{
$array1[$key] = $val;
}
}
print_r($array1);
print_r($array2);
Demo
The simplest thing to do is to use a foreach loop.
$array = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
$array1 = [];
$array2 = [];
foreach ($array as $key => $value)
// If value is 1, add to array1
// If value is not 1, add value to array2
if ($value === '1')
$array1[$key] = $value;
else
$array2[$key] = $value;
echo var_dump($array1);
echo '<br>';
echo var_dump($array2);
Use indirect reference:
$arrayAll = array("156"=>"1", "157"=>"1", "158"=>"2", "159"=>"1", "160"=>"2", "161"=>"1");
foreach($arrayAll as $key=>$value) {
$name = "array".$value;
$$name[$key] = $value;
}
echo "<pre>";
print_r($array1);
print_r($array2);
echo "</pre>";
//your array
$yourArray = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
With the conditions you mentioned just build two arrays, you can use array_keys with the second parameter that accepts a search value
$array1 = array_keys($yourArray, '1');
$array2 = array_keys($yourArray, '2');
If you don't want to use array_keys, go for an iteration
$array1 = array();
$array2 = array();
foreach($yourArray as $key=>$value){
//will always be 1 or 2, so an if-else is enought
if($value == 1){
$array1[] = $key;
} else {
$array2[] = $key;
}
}
And that's it.
Check this link for array_keys
If you have more than 2 values, the following will work and can be reused for other cases
You want to group them according to the values
$arrayOfValues = array_values($yourArray);
//this returns only the values of the array
$arrayOfUniqueValues = array_unique($arrayOfValues);
//this returns an array with the unique values, also with this u consider
//the posibility for more different values
//also u can get the unique values array on a single line
$arrayIfUniqueValues = array_unique(array_values($yourArray));
The array you will return
$theReturn = array();
foreach($arrayOfUniqueValues as $value ){
//what does this do?
//for each iteration it creates a key in your return array "$theReturn"
//and that one is always equal to the $value of one of the "Unique Values"
//array_keys return the keys of an array, and with the second parameter
//it acceps a search parameter, so the keys it return are the ones
//that matches the value, so here u are getting the array already made
$theReturn[$value] = array_keys($yourArray, $value);
}
The var_dump, in this case, will look like this
array(2) {
[1]=>
array(4) {
[0]=>
int(156)
[1]=>
int(157)
[2]=>
int(159)
[3]=>
int(161)
}
[2]=>
array(2) {
[0]=>
int(158)
[1]=>
int(160)
}
}
Hope my answer helps you, I tried to organize the solutions starting with the shortest/simplest.
Edit:
I forgot you needed the key value too, at least in this solution the array is always referring to the value, like $array1, $array2 or the $key references to the value as in the last solution
The simplest solution for separating an array into others based on the values involves:
Getting its unique values using array_unique.
Looping over these values using foreach.
Getting the key-value pairs intersecting with the current value using array_intersect.
Code:
# Iterate over every value and intersect it with the original array.
foreach(array_unique($arrayAll) as $v) ${"array$v"} = array_intersect($arrayAll, [$v]);
Advantage:
The advantage of this answer when compared to other given answers is the fact that it uses array_unique to find the unique values and therefore iterates only twice instead of n times.
Check out a live demo here.
Related
This question already has answers here:
Create nested array by array of keys
(3 answers)
Closed 6 years ago.
I have an array like so:
$input = array("visit", "outdoor", "parks-trailer");
$input_content = "A Value for last array element for input array."
$another_input = array("visit", "outdoor");
$another_input_content = "A Value for last array element for $input_content array."
And I have some text to assign to the last element of the array, once built.
Basically, what I need is the returned array to be like this:
$output = array(
"visit" => array(
"outdoor" => array(
"A Value for last array element for $input_content array."
"parks-trailer" => "A Value for last array element for input array."
)
)
);
How can I do this from values of an $input array that will always be 1 dimensional.
$content = 'My Value';
$output = array();
$flipped = array_flip($input);
$count = count($input) - 1;
foreach($flipped as $key => $flip)
{
if ($count >= $key)
$output[$key] = $content;
else
$output[$key] = array();
}
The problem here is that array_flip does work, but it doesn't do multidimensional here? And so array_flip transforms to array('visit' => 0, 'outdoor' => 1, 'parks-trailer' => 2), but I'm at a loss on how to get it to do multidimensional array, not singular.
I need to loop through multiples of these and somehow merge them into a global array, the answer given in here is not the same.
So, I need to merge each 1 of these into another array, keeping the values, if they exist. array_merge does not keep the values, array_merge_recursive does not keep the same key structure. How to do this?
I'm not sure sure why you would want such thing, but this is an option:
$ar = ['a', 'b', 'c'];
function arrayMagicFunction($ar, $last_string = 'STRING') {
$ret = $last_string;
$ar = array_reverse($ar);
foreach ($ar as $v) {
$ret = [$v => $ret];
}
return $ret;
}
var_dump(arrayMagicFunction($ar, 'A Value here'));
Output:
array(1) {
'a' =>
array(1) {
'b' =>
array(1) {
'c' =>
string(12) "A Value here"
}
}
}
I have an array as the following:
function example() {
/* some stuff here that pushes items with
dynamically created key strings into an array */
return array( // now lets pretend it returns the created array
'firstStringName' => $whatEver,
'secondStringName' => $somethingElse
);
}
$arr = example();
// now I know that $arr contains $arr['firstStringName'];
I need to find out the index of $arr['firstStringName'] so that I am able to loop through array_keys($arr) and return the key string 'firstStringName' by its index. How can I do that?
If you have a value and want to find the key, use array_search() like this:
$arr = array ('first' => 'a', 'second' => 'b', );
$key = array_search ('a', $arr);
$key will now contain the key for value 'a' (that is, 'first').
key($arr);
will return the key value for the current array element
http://uk.php.net/manual/en/function.key.php
If i understand correctly, can't you simply use:
foreach($arr as $key=>$value)
{
echo $key;
}
See PHP manual
If the name's dynamic, then you must have something like
$arr[$key]
which'd mean that $key contains the value of the key.
You can use array_keys() to get ALL the keys of an array, e.g.
$arr = array('a' => 'b', 'c' => 'd')
$x = array_keys($arr);
would give you
$x = array(0 => 'a', 1 => 'c');
Here is another option
$array = [1=>'one', 2=>'two', 3=>'there'];
$array = array_flip($array);
echo $array['one'];
Yes you can infact php is one of the few languages who provide such support..
foreach($arr as $key=>$value)
{
}
if you need to return an array elements with same value, use array_keys() function
$array = array('red' => 1, 'blue' => 1, 'green' => 2);
print_r(array_keys($array, 1));
use array_keys() to get an array of all the unique keys.
Note that an array with named keys like your $arr can also be accessed with numeric indexes, like $arr[0].
http://php.net/manual/en/function.array-keys.php
you can use key function of php to get the key name:
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
like here : PHP:key - Manual
I have 2 arrays.
<?php
$array1 = array('id' => 1, 'email' => 'example#example.com' , 'name' => 'john' );
$array2 = array('id', 'email');
i am having trouble writing a code to unset the key value pair from array1 that is not from array 2.
The problem with this is unlike most examples, my array2 does not have a format of a key value pair but only key.
How do i go about removing things from array1 that is not specified in array2.
my current code is not working
foreach ($array1 as $key => $value) {
if (array_search($key, $array2)===false) {
unset($key);
}
}
Use array_diff_key() to leave values which are not in second array:
$array1 = array('id'=>1, 'email'=> 'email' , 'name'=>'john' );
$array2 = array('id','email');
$result = array_diff_key($array1, array_flip($array2));
Or, if you want to change first array:
$array1 = array_diff_key($array1, array_flip($array2));
Edit (misunderstanding)
Use array_intersect_key() to leave values which are in second array:
$array1 = array_intersect_key($array1, array_flip($array2));
You are doing it right, just that your way of unset is incorrect:
unset($key);
should be
unset($array1[$key]);
Demo
You have to unset the element by its index (starting from 0)
For example
unset($array2[1]);
will remove the 'email' element.
So in Your case it should be:
unset($array1[$key]);
I was wondering about this kind of situation.
What if i have a huge array say about 50k items or more.
Now let's say many of that array keys have prefix let's name it settings_, now if i want to select all values where key begins by settings_ would i need to loop trough all 50k items or is there a better way?
And say there is some "magical" way to do this with single level arrays, what about multidimensional ones?
There is preg_grep, which matches array values. Since you want to search keys, you need to invert keys and values with array_flip:
<?php
$array = array(
'armenia' => 0,
'argentina' => 1,
'brazil' => 2,
'bolivia' => 3,
'congo' => 4,
'denmark' => 5
);
$filtered = array_flip(preg_grep('/^b/', array_flip($array)));
var_dump($filtered);
/*
Output:
array(2) {
["brazil"]=>
int(2)
["bolivia"]=>
int(3)
}
*/
$arr_main_array = array('something_test' => 123, 'other_test' => 456, 'something_result' => 789);
foreach($arr_main_array as $key => $value){
$exp_key = explode('_', $key);
if($exp_key[0] == 'something'){
$arr_result[] = $value;
}
}
if(isset($arr_result)){
print_r($arr_result);
}
You can execute the code at
http://sandbox.onlinephpfunctions.com/code/884816dd115b3ccc610e1732e9716471a7b29b0f
I have an array as the following:
function example() {
/* some stuff here that pushes items with
dynamically created key strings into an array */
return array( // now lets pretend it returns the created array
'firstStringName' => $whatEver,
'secondStringName' => $somethingElse
);
}
$arr = example();
// now I know that $arr contains $arr['firstStringName'];
I need to find out the index of $arr['firstStringName'] so that I am able to loop through array_keys($arr) and return the key string 'firstStringName' by its index. How can I do that?
If you have a value and want to find the key, use array_search() like this:
$arr = array ('first' => 'a', 'second' => 'b', );
$key = array_search ('a', $arr);
$key will now contain the key for value 'a' (that is, 'first').
key($arr);
will return the key value for the current array element
http://uk.php.net/manual/en/function.key.php
If i understand correctly, can't you simply use:
foreach($arr as $key=>$value)
{
echo $key;
}
See PHP manual
If the name's dynamic, then you must have something like
$arr[$key]
which'd mean that $key contains the value of the key.
You can use array_keys() to get ALL the keys of an array, e.g.
$arr = array('a' => 'b', 'c' => 'd')
$x = array_keys($arr);
would give you
$x = array(0 => 'a', 1 => 'c');
Here is another option
$array = [1=>'one', 2=>'two', 3=>'there'];
$array = array_flip($array);
echo $array['one'];
Yes you can infact php is one of the few languages who provide such support..
foreach($arr as $key=>$value)
{
}
if you need to return an array elements with same value, use array_keys() function
$array = array('red' => 1, 'blue' => 1, 'green' => 2);
print_r(array_keys($array, 1));
use array_keys() to get an array of all the unique keys.
Note that an array with named keys like your $arr can also be accessed with numeric indexes, like $arr[0].
http://php.net/manual/en/function.array-keys.php
you can use key function of php to get the key name:
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
like here : PHP:key - Manual