PHP array next value of a value - php

How to get next value of a value from array.
I have one array like this
$items = array(
'1' => 'two',
'9' => 'four',
'7' => 'three',
'6'=>'seven',
'11'=>'nine',
'2'=>'five'
);
how to get next value of 'four' or 'nine'.

I have this
$input = "nine";
$items = array(
'1' => 'two',
'9' => 'four',
'7' => 'three',
'6'=>'seven',
'11'=>'nine',
'2'=>'five'
);
$keys = array_keys($items);
$size = count($keys);
$foundKey = array_search($input,$items);
if($foundKey !== false)
{
$nextKey = array_search($foundKey,$keys)+1;
echo "your input is: ".$input."\n";
echo "it's key is: ".$foundKey."\n";
if($nextKey < $size)
{
echo "the next key => value is: ".$keys[$nextKey]." => ".$items[$keys[$nextKey]]."\n";
}
else
{
echo "there are no more keys after ".$foundKey;
}
}
the idea is that because the keys are not in any real order i need to make an easy to traverse order by getting all the keys and putting them into an array so that their integer keys are our order. this way '1' = 0, '9' = 1, '11' = 4.
from there i then locate which key matches our input. if i find it i get the position of that key and + 1 (the next key). from there i can reference the data in $items using the string value in $keys at the position of our input +1.
if our input is 'five' we run into a problem as 'five' is the last value in our array. so the last if statement checks if the index for the next key is less than the number of keys since the largest index we'll have is 5 and the number of keys we have is 6.
while you could use array_values to get all the values into an array using ordered integer keys by doing this you loose your original keys unless you also used array_keys. if you use array_keys first then there's really no need to use array_values

hope this help:
while (($next = next($items)) !== NULL) {
if ($next == 'three') {
break;
}
}
$next = next($items);
echo $next;
for large array u can use :
$src = array_search('five',$items); // get array key
$src2 = array_search($src,array_keys($items)); // get index array (start from 0)
$key = array_keys($items); // get array by number, not associative anymore
// then what u need just insert index array+1 on array by number ($key[$src2+1])
echo $items[$key[$src2+1]];

If that's the case, you should first prepare your array. Based on your given array, it seems the index is not consecutively correct. Try using array_values() function.
$items = array(
'1' => 'two',
'9' => 'four',
'7' => 'three',
'6'=>'seven',
'11'=>'nine',
'2'=>'five'
);
$new_items = array_values($items);
$new_items = array(
[0] => 'two',
[1] => 'four',
[2] => 'three',
[3] => 'seven',
[4] => 'nine',
[5] =>'five'
);
Then you can do the foreach..
foreach($new_items as $key => $value) {
// Do the code here using the $key
}

Related

Split an array into two arrays based on identical values

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.

Array combined with another array - how to do this elegantly

I've got two arrays, an array of integers and an array of strings. I want to combine these two, but this is proving troublesome to me.
Basically, the first value in each array will be associated, the second value of each array will be associated, third with each other, and so on.
I've got a foreach loop iterating over and using $result as array key, as such:
foreach ($results as $result) {
And then a function to generate $order based on said string.
I am then trying to associate each value as I said, where I would have something like:
array('8' => 'value', '8' => 'value', '6' => 'anothervalue', '6' => 'anothervalue');
Here's the code I have.
$order = resource_library_apachesolr_resource_type_order($resource_type);
$result['resource_type'] = $resource_type;
$newresults = array($order => $result);
$order isn't iterating, so how would I make it so that I get the iterated value of $order combined with the currently iterating value of $result?
Well, since you have repeated keys, you can't use array_combine
You might have to get a bit creative. Maybe casting to string and adding 0 before the integer part...
EXAMPLE:
$a1 = array(1,1,2,3,3);
$a2 = array('a', 'b', 'c', 'd', 'e');
$a3 = array();
for ($i=0; $i<count($a1); ++$i) {
$key = (string) $a1[$i];
$val = (String) $a2[$i];
while (isset($a3[$key])) {
$key = "0$key";
}
$a3[$key] = $val;
}
var_dump($a3);
foreach ($a3 as $key => $val) {
$key = (int) $key;
print "$key=>$val<br>";
}
OUTPUTS:
array (size=5)
1 => string 'a' (length=1)
'01' => string 'b' (length=1)
2 => string 'c' (length=1)
3 => string 'd' (length=1)
'03' => string 'e' (length=1)
1=>a
1=>b
2=>c
3=>d
3=>e
I don't know why you need this, but if I want to do something like that I'll do:
$arr = array();
foreach($numbers as $i=>$num){
$arr[$num][] = $strings[$i];
}
and will get:
array(
1 => array(
a,
b
),
2 => array(
c
),
3 => array(
d,
e
)
)

php. array_values function. how to get mapping from old keys to new keys?

There is function array_values in PHP such that
$array2 = array_values($array1);
$array2 has the same values as $array1 but keys are from
0 to sizeof($array1) - 1. Is it possible to get mapping from old keys to new keys?
EDIT. I will explain on an example:
$array1 = array( 'a' => 'val1', 'b' => 'val1');
$array2 = array_values( $array1 );
so now array2 has next values
$array2[0] = 'val1'
$array2[1] = 'val2'
How get array3 such that:
$array3['a'] = 0
$array3['b'] = 1
To produce a key map you need to first get the keys into a regular array and then flip the keys and values:
$array1_keymap = array_flip(array_keys($array1));
For example:
$array1 = array(
'a' => 123,
'b' => 567,
);
$array1_values = array_values($array1);
$array1_keymap = array_flip(array_keys($array1));
Value of $array1_values:
array(
0 => 123,
1 => 567,
);
Value of $array1_keymap:
array(
'a' => 0,
'b' => 1,
);
So:
$array1['a'] == $array1_values[$array1_keymap['a']];
$array1['b'] == $array1_values[$array1_keymap['b']];
Yes, as simple as
$array2 = $array1;
In this case you would get both values and keys like they are in the original array.
$keyMapping = array_combine(array_keys($array1), array_keys($array2));
This the keys of $array1 and maps them to the keys of $array2 like so
<?php
$array1 = array(
'a' => '1',
'b' => '2',
);
$array2 = array_values($array1);
print_r(array_combine(array_keys($array1), array_keys($array2)));
Array
(
[a] => 0
[b] => 1
)
You can use:
$array3 = array_keys($array1);
Now $array3[$n] is the key of the value in $array2[$n] for any 0 <= $n < count($array1). You can use this to determine which keys were in which places.
If you want to keep the same value of array1 but change the key to index numbers, try this:
$array2 = array();
foreach ($array1 as $key => $value){
$array2[] = $value;
// or array_push($array2, $value);
}
var_dump($array2);

Hard PHP nut : how to insert items into one associate array?

Yes, this is a bit of a trick question; one array (without copies), as opposed to any odd array. Let me explain, so let's start here ;
$a = array ( 'one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5, 'six' => 6 ) ;
Pretend that this array is long, over a hundred long. I loop through it, step by step, but at some point (let's make up that this happens at the second item) something happens. Maybe the data is funky. Nevertheless, we need to add some items to it for later processing, and then keep looping through it, without losing the current position. Basically, I would like to do something like this ;
echo current ( $a ) ; // 'two'
array_insert ( $a, 'four', 'new_item', 100 ) ;
echo current ( $a ) ; // 'two'
Definition for array_insert is ( $array, $key_where_insert_happens, $new_key, $new_value ) ; Of course $new_key and $new_value should be wrapped in an array wrapper, but that's besides the point right now. Here's what I want to see happening after the above code having ran ;
print_r ( $a ) ; // array ( 'one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'new_item' => 100, 'five' => 5, 'six' => 6 ) ;
echo current ( $a ) ; // 'two'
Whenever you use array_splice, array_slice, array_push or most of the other array fiddling functions, you basically create a copy of the array, and then you can copy it back, but this breaks the reference to the original array and the position as well, and my loop above breaks. I could use direct reference (ie. $a['new_item'] = 'whatever;) or put it at the end, but none of these will insert items into a given position.
Any takers? How can I do a true insert into an associative array directly (that's being processed elsewhere)? My only solution so far is to ;
record the position (current())
Do the splice/insert (array_slice)
overwrite old array with new ($old = $new)
search the new position (first reset() then looping through to find it [!!!!!!])
Surely there's a better, simpler and more elegant way for doing something that's currently kludgy, heavy and poorly hobbled together? Why isn't there a array_set_position ( $key ) function that quickly can help this out, or an array_insert that works directly on the same array (or both)?
Maybe I'm not understanding you correctly but have you looked into array_splice()?
This answer might also interest you.
Would something like this work?
function array_insert($input, $key, $value)
{
if (($key = array_search($key, array_keys($input))) !== false)
{
return array_splice($input, $key, 1, $value);
}
return $input;
}
This was the best I could come up with:
$a = array
(
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6,
);
ph()->Dump(next($a)); // 2
array_insert($a, 'four', array('new_item' => 100));
ph()->Dump(current($a)); // 2
function array_insert(&$array, $key, $data)
{
$k = key($array);
if (array_key_exists($key, $array) === true)
{
$key = array_search($key, array_keys($array)) + 1;
$array = array_slice($array, null, $key, true) + $data + array_slice($array, $key, null, true);
while ($k != key($array))
{
next($array);
}
}
}
ph()->Dump($a);
/*
Array
(
[one] => 1
[two] => 2
[three] => 3
[four] => 4
[new_item] => 100
[five] => 5
[six] => 6
)
*/
I don't think it's possible to set an array internal pointer without looping.
Rather than using the associative array as the event queue, keep a separate integer-indexed array. Loop over an explicit index variable rather than using the internal array position.
$events = array_keys($a);
for ($i=0; $i < count($events); ++$i) {
...
/* if there's an event to add after $j */
array_splice($events, $j+1, 0, array($new_event_key));
$a[$new_event_key] = $new_event_data;
...
}
To keep things more cohesive, you can package the two arrays into an event queue class.

array_splice() - Numerical Offsets of Associative Arrays

I'm trying to do something but I can't find any solution, I'm also having some trouble putting it into works so here is a sample code, maybe it'll be enough to demonstrate what I'm aiming for:
$input = array
(
'who' => 'me',
'what' => 'car',
'more' => 'car',
'when' => 'today',
);
Now, I want to use array_splice() to remove (and return) one element from the array:
$spliced = key(array_splice($input, 2, 1)); // I'm only interested in the key...
The above will remove and return 1 element (third argument) from $input (first argument), at offset 2 (second argument), so $spliced will hold the value more.
I'll be iterating over $input with a foreach loop, I know the key to be spliced but the problem is I don't know its numerical offset and since array_splice only accepts integers I don't know what to do.
A very dull example:
$result = array();
foreach ($input as $key => $value)
{
if ($key == 'more')
{
// Remove the index "more" from $input and add it to $result.
$result[] = key(array_splice($input, 2 /* How do I know its 2? */, 1));
}
}
I first though of using array_search() but it's pointless since it'll return the associative index....
How do I determine the numerical offset of a associative index?
Just grabbing and unsetting the value is a much better approach (and likely faster too), but anyway, you can just count along
$result = array();
$idx = 0; // init offset
foreach ($input as $key => $value)
{
if ($key == 'more')
{
// Remove the index "more" from $input and add it to $result.
$result[] = key(array_splice($input, $idx, 1));
}
$idx++; // count offset
}
print_R($result);
print_R($input);
gives
Array
(
[0] => more
)
Array
(
[who] => me
[what] => car
[when] => today
)
BUT Technically speaking an associative key has no numerical index. If the input array was
$input = array
(
'who' => 'me',
'what' => 'car',
'more' => 'car',
'when' => 'today',
'foo', 'bar', 'baz'
);
then index 2 is "baz". But since array_slice accepts an offset, which is not the same as a numeric key, it uses the element found at that position in the array (in order the elements appear), which is why counting along works.
On a sidenote, with numeric keys in the array, you'd get funny results, because you are testing for equality instead of identity. Make it $key === 'more' instead to prevent 'more' getting typecasted. Since associative keys are unique you could also return after 'more' was found, because checking subsequent keys is pointless. But really:
if(array_key_exists('more', $input)) unset($input['more']);
I found the solution:
$offset = array_search('more', array_keys($input)); // 2
Even with "funny" arrays, such as:
$input = array
(
'who' => 'me',
'what' => 'car',
'more' => 'car',
'when' => 'today',
'foo', 'bar', 'baz'
);
This:
echo '<pre>';
print_r(array_keys($input));
echo '</pre>';
Correctly outputs this:
Array
(
[0] => who
[1] => what
[2] => more
[3] => when
[4] => 0
[5] => 1
[6] => 2
)
It's a trivial solution but somewhat obscure to get there.
I appreciate all the help from everyone. =)
$i = 0;
foreach ($input as $key => $value)
{
if ($key == 'more')
{
// Remove the index "more" from $input and add it to $result.
$result[] = key(array_splice($input, $i , 1));
}
$i++;
}

Categories