Grab ordinal number of the array value inside foreach - php

Hello,
I want to grab the ordinal number of an array key inside a foreach loop.
Example
<?php
$array = array("id" => 2, "username" => "foobar");
foreach($array as $value){
$array_key = search_array($value, $array);
//find the ordinal number of $array_key from $array here.
echo $value;
}
count returns the entire number of array keys in the array, i need to grab the ordinal number of the array key.
I hope you guys understand what i ask.

From what I understand, if an entry has a string key, it doesn't have an ordinal position in the array. From http://php.net/manual/en/language.types.array.php:
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
Ordered maps don't assign ordinal keys on top of the already existing string keys.
What you could do though, to get a psuedo-ordinal-key is increment a variable.
$i=0;
foreach( $array as $key => $value ) {
echo $i.':'.$key.':'.$value;
$i++;
}
Will echo out each ordinal key, key, and value in the array.

Have another variable that will increase in value after each iteration.

You can use the current function like so:
foreach($array as $value){
$array_key = search_array($value, $array);
echo current( $array );
echo $value;
}
Or you can just add a counter to your loop like so:
$count = 0;
foreach($array as $value){
$array_key = search_array($value, $array);
echo $count++;
echo $value;
}

<?php
$arry = array("id" => 2; "username" => "foobar");
$idx = 0;
foreach($array as $value){
if(array_search(arry, $value)) echo "element found: ".$idx;
$idx++;
}
?>
What you need is another variable - $idx in the above example to count the iterations, as you can't use the "key" corresponding to the value as they're named.
Also the search function is called array_search indeed.

Related

Find pairings in a two-dimensional array

I have a two-dimensional array and look for a way to find the all double entries. E.g. if the array is of the form
$a = array(
array('a','b','c'),
array('d','a','e'),
array('d','c','b')
)
the function should return the list
array(array(0,0),array(1,1)) // Since $a[0,0]=$a[1,1]
array(array(0,1),array(2,2)) // Since $a[0,1]=$a[2,2]
array(array(0,2),array(2,1)) // Since $a[0,2]=$a[2,1]
array(array(1,0),array(2,0)) // Since $a[1,0]=$a[2,0]
array(1,2) // Unmatched
Is there an elegant/efficient way to implement this?
With a nested loop. Use the values as keys in the result and append the coordinates as arrays under those keys.
foreach ($a as $x => $inner) {
foreach ($inner as $y => $value) {
$result[$value][] = [$x, $y];
}
}
The $result will contain sets of coordinates for all the given values. You can group the results by size of set to identify which values are unmatched, pairs, or have even greater than two occurrences (if that's possible).
foreach ($result as $value => $set) {
$sets[count($set)][$value] = $set;
}

Combine 2 arrays into 2d array without losing data

I have 2 arrays and want to combine into third array with one array as key and another as value. I tried to use array_combine(), but the function will eliminate all the repeated keys, so I want the result array as a 2d array. The sample array is as below:
$keys = {0,1,2,0,1,2,0,1,2};
$values = {a,b,c,d,e,f,g,h,i};
$result = array(
[0]=>array(0=>a,1=>b,2=>c),
[1]=>array(0=>d,1=>e,2=>f),
[2]=>array(0=>g,1=>h,2=>i)
);
//What i am using right now is:
$result = array_combine($keys,$values);
But it only returns array(0=>g,2=>h,3=>i). Any advice would be appreciated!
You can do it like below:-
<?php
$keys = array(0,1,2,0,1,2,0,1,2);
$values = array('a','b','c','d','e','f','g','h','i');
$values = array_chunk($values,count(array_unique($keys)));
foreach($values as &$value){
$value = array_combine(array_unique($keys),$value);
}
print_r($values);
https://eval.in/859753
Yes the above is working and i give upvote too for this but i dont know why you combine into the foreach loop its not necessary. The results are given in only in second line. Can you describe?
<?php
$keys = array(0,1,2,0,1,2,0,1,2);
$values = array('a','b','c','d','e','f','g','h','i');
$v = array_chunk($values,count(array_unique($keys)));
echo "<pre>";print_r($v);
?>
https://eval.in/859759
As a more flexible/robust solution, push key-value pairs into new rows whenever the key's value is already in the currently targeted row. In other words, there will never be an attempt to write a key into a row that already contains that particular key.
This can be expected to be highly efficient because there are no iterated function calls ...no function calls at all, really.
Code: (Demo)
$result = [];
foreach ($keys as $i => $key) {
$counter[$key] = ($counter[$key] ?? -1) + 1;
$result[$counter[$key]][$key] = $values[$i];
}
var_export($result);

get multidimensional array value from keys in another array

I've got an array containing values I wish to use as keys, such as:
$keys = array("first", "second", "third", "fourth");
The count and contents of these values will be changing dynamically within a loop. I want them to become the keys of a multidimensional array, but the count of the keys array will always be changing, so while this would work for that first array of keys:
$multidimensional[$keys[0]][$keys[1]][$keys[2]][$keys[3]] = "some value";
Later in the loop the keys may be something like:
$keys = array("first", "second", "gamma", "delta", "theta", "kappa");
So using this in the loop:
$multidimensional[$keys[0]][$keys[1]][$keys[2]][$keys[3]] = "some value";
Will not work, and needs to be dynamic too based on the count of the keys.
I've gone through each of the array functions in the PHP manual and can't seem to find something that fulfills this purpose. Am I totally overlooking something basic here? Maybe some curly brace magic?
There you go...
function setMultidimensionalValue($value, array $keys, array $multidimensional)
{
$node = &$multidimensional;
foreach ($keys as $key)
{
if (!isset($node[$key]))
$node[$key] = null;
$node = &$node[$key];
}
$node = $value;
return $multidimensional;
}
// Example of usage
$multidimensional = array();
var_dump(setMultidimensionalValue('value', array('first', 'second', 'third'), $multidimensional));

How can I delete array elements inside foreach loop?

I have a foreach loop and I would like to completely remove the array elements that satisfy the criteria, and change the keys to stay sequential 1,2,3,4.
I have:
$thearray = array(20,1,15,12,3,6,93);
foreach($thearray as $key => $value){
if($value < 10){
unset($thearray[$key]);
}
}
print_r($thearray);
But this keeps the keys as they were before. I want to make them 1,2,3,4, how can this be achieved?
Reset the array indices with array_values():
$thearray = array_values( $thearray);
print_r($thearray);
You can just use array_filter to remove the array elements that satisfy the criteria
$thisarray = array_filter($thearray,function($v){ return $v > 10 ;});
Then use array_values change the keys to stay 0, 1,2,3,4 .... as required
$thisarray = array_values($thisarray);
Build up a new array and then assign that to your original array after:
$thearray=array(20,1,15,12,3,6,93);
$newarray=array();
foreach($thearray as $key=>$value){
if($value>=10){
$newarray[]=$value
}
}
$thearray=$newarray;
print_r($thearray);

How to get Array index in foreach

I have a foreach loop in php to iterate an associative array. Within the loop, instead of increamenting a variable I want to get numeric index of current element. Is it possible.
$arr = array('name'=>'My name','creditcard'=>'234343435355','ssn'=>1450);
foreach($arr as $person){
// want index here
}
I usually do this to get index:
$arr = array('name'=>'My name','creditcard'=>'234343435355','ssn'=>1450);
$counter =0;
foreach($arr as $person){
// do a stuff
$counter++;
}
Use this syntax to foreach to access the key (as $index) and the value (as $person)
foreach ($arr as $index => $person) {
echo "$index = $person";
}
This is explained in the PHP foreach documentation.
Why would you need a numeric index inside associative array? Associative array maps arbitrary values to arbitrary values, like in your example, strings to strings and numbers:
$assoc = [
'name'=>'My name',
'creditcard'=>'234343435355',
'ssn'=>1450
];
Numeric arrays map consecutive numbers to arbitrary values. In your example if we remove all string keys, numbering will be like this:
$numb = [
0=>'My name',
1=>'234343435355',
2=>1450
];
In PHP you don't have to specify keys in this case, it generates them itself.
Now, to get keys in foreach statement, you use the following form, like #MichaelBerkowski already shown you:
foreach ($arr as $index => $value)
If you iterate over numbered array, $index will have number values. If you iterate over assoc array, it'll have values of keys you specified.
Seriously, why I am even describing all that?! It's common knowledge straight from the manual!
Now, if you have an associative array with some arbitrary keys and you must know numbered position of the values and you don't care about keys, you can iterate over result of array_values on your array:
foreach (array_values($assoc) as $value) // etc
But if you do care about keys, you have to use additional counter, like you shown yourself:
$counter = 0;
foreach ($assoc as $key => $value)
{
// do stuff with $key and $value
++$counter;
}
Or some screwed functional-style stuff with array_reduce, doesn't matter.

Categories