Let's assume I know that there is key "twoVal", but I do not know what is after it. How do I get to the next key for that matter? Shoud I know the position of key "twoVal"? Or there is another way around?
$arr = array('Cool Viski' => array('oneVal' => '169304',
'twoVal' => '166678',
'threeVal' => '45134'));
$keys = array_keys($arr['Cool Viski']);
$position = array_search('twoVal', $keys);
if (isset($keys[$position + 1])) {
$keyAfterTwoVal = $keys[$position + 1];
}
$arr = array('Cool Viski' => array('oneVal' => '169304',
'twoVal' => '166678',
'threeVal' => '45134'));
foreach($arr as $s=>$v){
foreach($v as $val){
if(key($v) == "twoVal"){
$t=next($v);
print "next key: ".key($v)."\n";
print "next key value is: ".$t."\n";;
}else{
next($v);
}
}
}
You might be interested in the various array seeking functions, but unless a PHP array is indexed only by integers there's no guarantee of order on the keys.
Related
I'm trying to find out wich variable is bigger (those are all integers):
<?php
$ectoA=3;
$ectoB=5;
$mesoA=0;
$mesoB=4;
$endoA=11;
$endoB=11;
echo max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
I tried with max but it gives the value and not the $varName.
I want to get the name of the variable and if there are two that are equal I need both.
Thanks for the help.
As suggested i tried this and worked but still got to know if I have two MAX values I need to do something else...
$confronto = [
'ectoA' => $ectoA,
'ectoB' => $ectoB,
'endoA' => $endoA,
'endoB' => $endoB,
'mesoA' => $mesoA,
'mesoB' => $mesoB,
];
$result= array_keys($confronto,max($confronto));
$neurotipo = $result[0];
echo $neurotipo;
I want endoA and endoB to be identified...
You can define an array instead, or compact your variables into an array:
//$array = array('ectoA'=>3,'ectoB'=>5,'mesoA'=>0,'mesoB'=>4,'endoA'=>11,'endoB'=>11);
$array = compact('ectoA','ectoB','mesoA','mesoB','endoA','endoB');
$result = array_keys($array, max($array));
Then compute the max() of that array and use array_keys() to search for the max number and return the keys.
print_r($result);
Yields:
Array
(
[0] => endoA
[1] => endoB
)
I would definitely recommend using an array. Then you can do something like this:
$my_array = array(3, 5, 0, 4, 11, 11);
$maxIndex = 0;
for($i = 1; $i < count($my_array); $i++) {
if($my_array[$i] > $my_array[$maxIndex])
$maxIndex = $i;
}
Another option with array keys would be:
$my_array = array("ectoA" => 3, "ectoB" => 5, "mesoA" => 0, "mesoB" => 4, "endoA" => 11, "endoB" => 11);
$maxIndex = "ectoA";
while($c = current($my_array)) {
$key = key($my_array);
if($my_array[$key] > $my_array[$maxIndex])
$maxIndex = $key;
next($my_array);
}
Note: Code not tested, but should be the gist of what needs to be done
use the array like this
<?php
$value= array (
"ectoA" =>3,
"ectoB"=>5,
"mesoA"=>0,
"mesoB"=>4,
"endoA"=>11,
"endoB"=>11);
$result= array_keys($value,max($values))
print_r($result);
?>
As per the documentation, Since the two values are equal, the order they are provided determines the result $endoA is the biggest here.
But I am not sure your intention is to find the biggest value or which variable is the highest
Your code seems to be a working one.
But it would print for you the value of the maximum number, not the name of the variable.
To have the name of the variable at the end you should add some additional code like:
$max = (max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
if($max == $ectoA) echo "ectoA";
if($max == $ectoB) echo "ectoB";
// ... same goes for other variables
But working with an array would be the most proper solution.
Hello guys i have coded something like this ..I just dont know wheather the code is right or not ..But i have a question
THe code is
$featured = array('name' => 12,'yeah' => 10);
foreach($featured as $key => $value){
echo $value['name'];
}
I know that value of name can be acessed by $featured['name']
but now I just need to know wheather the key of array can be acessed with value like $value['name'].
Is it possbile like that ?..
Any help would be appreciated ..Thanks
$featured = array('name' => 12,'yeah' => 10);
foreach($featured as $key => $value){
echo $key; // outputs: name
echo " - ";
echo $value; // outputs: 12
echo "<br />";
}
Yes, it supports that in the next iteration of the loop.
Output:
name - 12
yeah - 10
BTW, one more way of accessing the keys from array.
$featured = array('name' => 12,'yeah' => 10);
while (current($featured)) {
echo key($featured).'<br />';
next($featured);
}
Output:
name
yeah
You most probably want to do:
echo "{$key} => {$value}";
The foreach($featured as $key => $value) statement iterates the array and for each iteration $key and $value contain both the key and value for the tuple.
Take a look at this:
http://php.net/array_search
it searches for the value and returns it's key.
It's not like accessing $array['value'] but it's still userfull if you want to find the key.
This is what I have tried:
foreach ($multiarr as $arr) {
foreach ($arr as $key=>$val) {
if (next($arr) === false) {
//work on last key
} else {
//work
}
}
}
After taking another look, I thinknext is being used wrong here, but I am not sure what to do about it.
Is it possible to see if I'm on the last iteration of this array?
$lastkey = array_pop(array_keys($arr));
$lastvalue = $arr[$lastkey];
If you want to use it in a loop, just compare $lastkey to $key
You will need to keep a count of iterations and check it against the length of the array you are iterating over. The default Iterator implementation in PHP does not allow you to check whether the next element is valid -- next has a void return and the api only exposes a method to check whether the current position is valid. See here http://php.net/manual/en/class.iterator.php. To implement the functionality you are thinking about you would have to implement your own iterator with a peek() or nextIsValid() method.
Try this:
foreach ($multiarr as $arr) {
$cnt=count($arr);
foreach ($arr as $key=>$val) {
if (!--$cnt) {
//work on last key
} else {
//work
}
}
}
See below url i think it help full to you:-
How to get last key in an array?
How to get last key in an array?
Update:
<?php
$array = array(
array(
'first' => 123,
'second' => 456,
'last' => 789),
array(
'first' => 123,
'second' => 456,
'last_one' => 789),
);
foreach ($array as $arr) {
end($arr); // move the internal pointer to the end of the array
$key = key($arr); // fetches the key of the element pointed to by the internal pointer
var_dump($key);
}
output:
string(4) "last" string(4) "last_one"
This function (in theory, I haven't tested it) will return the last and deepest key in a multidemnsional associative array. Give I a run, I think you'll like it.
function recursiveEndOfArrayFinder($multiarr){
$listofkeys = array_keys($multiarr);
$lastkey = end($listofkeys);
if(is_array($multiarr[$lastkey])){
recursiveEndOfArrayFinder($multiarr[$lastkey]);
}else{
return $lastkey;
}
}
So here's the input:
$in['a--b--c--d'] = 'value';
And the desired output:
$out['a']['b']['c']['d'] = 'value';
Any ideas? I've tried the following code without any luck...
$in['a--b--c--d'] = 'value';
// $str = "a']['b']['c']['d";
$str = implode("']['", explode('--', key($in)));
${"out['$str']"} = 'value';
This seems like a prime candidate for recursion.
The basic approach goes something like:
create an array of keys
create an array for each key
when there are no more keys, return the value (instead of an array)
The recursion below does precisely this, during each call a new array is created, the first key in the list is assigned as the key for a new value. During the next step, if there are keys left, the procedure repeats, but when no keys are left, we simply return the value.
$keys = explode('--', key($in));
function arr_to_keys($keys, $val){
if(count($keys) == 0){
return $val;
}
return array($keys[0] => arr_to_keys(array_slice($keys,1), $val));
}
$out = arr_to_keys($keys, $in[key($in)]);
For your example the code above would evaluate as something equivalent to this (but will work for the general case of any number of -- separated items):
$out = array($keys[0] => array($keys[1] => array($keys[2] => array($keys[3] => 'value'))));
Or in more definitive terms it constructs the following:
$out = array('a' => array('b' => array('c' => array('d' => 'value'))));
Which allows you to access each sub-array through the indexes you wanted.
$temp = &$out = array();
$keys = explode('--', 'a--b--c--d');
foreach ($keys as $key) {
$temp[$key] = array();
$temp = &$temp[$key];
}
$temp = 'value';
echo $out['a']['b']['c']['d']; // this will print 'value'
In the code above I create an array for each key and use $temp to reference the last created array. When I run out of keys, I replace the last array with the actual value.
Note that $temp is a REFERENCE to the last created, most nested array.
I have an array like
$myArray =array
(
"0"=>array("dogs",98),
"1"=>array("cats",56),
"2"=>array("buffaloes",78)
)
How can I get a key by providing a value?
e.g. if i search for "buffaloes" array_search may return "2".
Thanks
$myArray =array
(
"0"=>array("dogs",98),
"1"=>array("cats",56),
"2"=>array("buffaloes",78)
);
function findInArray($term, $array) {
foreach($array as $key => $val) {
if(in_array($term, $val, true)) {
return $key;
}
}
}
echo findInArray('buffaloes', $myArray); // 2
echo findInArray(78, $myArray); // 2
function asearch($key, $myArray) {
for ($i = 0; $i < sizeof($myArray); $i++) {
if ($myArray[$i][0] == $key) {
return $i;
}
}
return -1; # no match
}
Though, you'd probably want to restructure your array to:
$myarray = array(
'dogs' => 98,
'cats' => 56,
'buffaloes' => 78
);
And just do:
$myArray['buffaloes']; # 78
The only way you can do it is to iterate over every item and preform a Linear Search
$i = -1;
foreach ($myArray as $key => $item){
if ( $item[0] == 'buffaloes' ){
$i = $key;
break;
}
}
//$i now holds the key, or -1 if it doesn't exist
As you can see, it is really really inefficient, as if your array has 20,000 items and 'buffaloes' is the last item, you have to make 20,000 comparisons.
In other words, you need to redesign your data structures so that you can look something up using the key, for example a better way may be to rearrange your array so that you have the string you are searching for as the key, for example:
$myArray['buffaloes'] = 76;
Which is much much faster, as it uses a better data structure so that it only has to at most n log n comparisons (where n is the number of items in the array). This is because an array is in fact an ordered map.
Another option, if you know the exact value of the value you are searching for is to use array_search
I never heard of built in function. If you want something more general then above solutions you shold write your own function and use recursion. maybe array_walk_recursive would be helpful
You can loop over each elements of the array, testing if the first element of each entry is equal to "buffaloes".
For instance :
foreach ($myArray as $key => $value) {
if ($value[0] == "buffaloes") {
echo "The key is : $key";
}
}
Will get you :
The key is : 2
Another idea (more funny ?), if you want to whole entry, might be to work with array_filter and a callback function that returns true for the "bufalloes" entry :
function my_func($val) {
return $val[0] == "buffaloes";
}
$element = array_filter($myArray, 'my_func');
var_dump($element);
Will get you :
array
2 =>
array
0 => string 'buffaloes' (length=9)
1 => int 78
And
var_dump(key($element));
Gves you the 2 you wanted.