Get foreach numeric index when keys are named - php

This question is just for fun and out of curiosity.
Edit : My question is different than
How to find the foreach index
Because $key has already a non-numeric value in my case.
Without having a variable outside a foreach that is increment inside the foreach scope, as the usual $i, is there a way to get the index of an item when $key is already named ?
Exemples :
$myNumericIndexArray = ('foo', 'bar', 'go', 'habs');
foreach($myNumericIndexArray as $key => $value){
//Here $key will be 0 -> 1 -> 2 -> 3
}
Now, if I have :
$myNamedIndexArray = ('foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic');
foreach($myNamedIndexArray as $key => $value){
//Here $key will be foo -> go -> CSGO_bestTeam
}
Can I, without having to :
$i=0;
foreach($myNamedIndexArray as $key => $value){
//Here $key will be foo -> go -> CSGO_bestTeam
$i++;
}
access the index of a named array. Something declared in the foreach declaration like in a for or a status of $key ?
Have a good one.

If you really want index array of associative array than try this:
$myNamedIndexArray = ['foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic'];
$keys = array_keys($myNamedIndexArray);
foreach($myNamedIndexArray as $key => $value){
echo array_search($key, $keys);
}

I don't know why you would want to do an array_keys() and array_search() every loop iteration. Just build a reference array and you can still foreach() the original:
$positions = array_flip(array_keys($myNamedIndexArray));
foreach($myNamedIndexArray as $key => $value){
echo "{$key} => {$value} is position {$positions[$key]}\n";
}

Something like this :
<?php
$myNamedIndexArray = array('foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic');
$numericIndexArray = array_keys($myNamedIndexArray);
foreach($numericIndexArray as $key=>$value){
echo $key.'</br>'; //here key will be 0 1 2
echo $value. '</br>';
}

I'd try something like this:
<?php
$myNamedIndexedArray = ['foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic'];
$myNumberIndexedArray = array_keys($myNamedIndexedArray);
foreach($myNumberIndexedArray as $key => $value){
echo $key. " => " . $myNamedIndexedArray[$myNumberIndexedArray[$key]]."<br />";
}
?>
Adn the output will be:
0 => bar
1 => habs
2 => fnatic

Related

How to get first occurrence non zero key value pair from any associative array

I have an associative array:
$pair = array(
'S'=>'0',
'I'=>'50',
'P'=>'30'
);
From this pair of key and values, I need first occurrence non zero value from key value pair only,
from my example I'm expecting key I and value 50.
Do something like this:
function findNonZero($var){
// returns whether the input is non zero
return($var > 0);
}
$pair = array(
'S'=>'0',
'I'=>'50',
'P'=>'30'
);
$newPair = array_filter($pair, "findNonZero");
var_dump($newPair); //Contains array of non-zero values
You can do that with usual foreach loop
$pair = array(
'S'=>'0',
'I'=>'50',
'P'=>'30'
);
foreach($pair as $k=>$v) {
if ($v) break;
}
echo "$k => $v"; // I => 50
demo
You can use php functions array_filter(), array_slice(), or use a foreach loop.
<?php
// filter out empty values, and get first item
$value = array_slice(array_filter($pair), 0, 1);
// check not empty
if (!empty($value)) {
// get key
echo 'key => '.array_keys($value)[0].PHP_EOL;
// get value
echo 'value => '.array_values($value)[0];
}
https://3v4l.org/tr3bp
Result:
key => I
value => 50
Or use a loop:
<?php
$value = [];
foreach ($pair as $k => $v) {
if (!empty($v)) {
$value[$k] = $v;
break;
}
}
if (!empty($value)) {
echo 'key => '.array_keys($value)[0].PHP_EOL;
echo 'value => '.array_values($value)[0];
}
https://3v4l.org/tPeAq
Result:
key => I
value => 50
Or use a generator,
<?php
$getNoneEmpty = function() use ($pair) {
foreach ($pair as $key => $value) {
if (!empty($value)) {
yield [$key => $value];
}
}
};
// get first
$value = $getNoneEmpty()->current();
if (!empty($value)) {
echo 'key => '.array_keys($value)[0].PHP_EOL;
echo 'value => '.array_values($value)[0].PHP_EOL;
}
// or loop over all
foreach ($getNoneEmpty() as $value) {
echo 'key => '.array_keys($value)[0].PHP_EOL;
echo 'value => '.array_values($value)[0].PHP_EOL;
}
https://3v4l.org/mnnHl
Result:
key => I
value => 50
key => I
value => 50
key => P
value => 30
Many ways to skin a cat, though, if you don't want the key/value you can also do it differently.

Multidimensional array loop to get value

I have an array of multiple arrays all with different levels. What im trying to do is loop though the array by key, and it will go through each level getting the values for those keys. myArray looks something like this
Array ( [0] =>
Array ( [Date] => 2011-15-22
[Color] => blue
[Status] => Fresh
[1] =>
Array ( [Date] => 1999-08-04
[Color] => green
[Status] => Rotten) )
I have tried
foreach($myArray as $row){
foreach($row["Date"] as $k){
echo $k
}
}
I am getting an
Notice: Undefined index: Date
and
Warning: Invalid argument supplied for foreach()
Simply with array_walk_recursive function:
$arr = [
[ 'Date' => '2011-15-22', 'Color' => 'blue', 'Status' => 'Fresh' ],
[ 'Date' => '1999-08-04', 'Color' => 'green', 'Status' => 'Rotten' ]
];
array_walk_recursive($arr, function($v, $k){
if ($k == 'Date') echo $v . PHP_EOL;
});
The output:
2011-15-22
1999-08-04
On your foreach, you should specify the key and value so you can access both:
foreach ($myArray as $key => $value){
echo $key.' is '. gettype ($value).'<br>';
if (is_array($value)){
foreach ($value as $subKey => $subValue){
echo $subkey . ' => ' . $subValue . '<br>';
}
}
}
This way you can access and print all values without losing the structure
As axiac states in the comments, $row["Date"]is a String and therefore not iterable. You probably just want this:
foreach($myArray as $row){
foreach($row as $k){
echo $k
}
}
The Notice Undefined index: Date also describes what is going wrong - you are accessing the index without checking if it exists. It does look like that your data structure is not always the same. In this case you should always check the existence with the isset function:
if (isset($row["Date"])) {
//do something here
}
It looks like you just need this:
foreach($myArray as $row){
echo $row["Date"];
}
or
foreach($myArray as $row){
$k= $row["Date"];
//do stuff...
}
or
foreach($myArray as $row){
$k[]= $row["Date"];
}
// do stuff with $k[] array.
Warning: Invalid argument supplied for foreach()
Because $row["Date"] is string
foreach() - foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.
Notice: Undefined index: Date
Probably your array may not have element with key Date somewhere (your array structure probably different, as iteration takes place), so you are getting this message, use isset() to or array_key_exists() to validate, depending on the purpose.
Please note isset != array_key_exists
$a = array('key1' => 'test1', 'key2' => null);
isset($a['key2']); // false
array_key_exists('key2', $a); // true
There is another important difference. isset doesn't complain when $a does not exist, while array_key_exists does.

How to make a associative array from other associative array?

I need some help with another PHP problem I am working on. I won't be posting the exact question, as I'd prefer to try and apply the knowledge I get from here to solve my problem.
First:
I have an associative array. I must loop through the array to find the array values which have keys that begin with a specific string and push both the key and value to an output array.
eg:
- Loop through the below array & push all elements which have a key beginning with "edible_" to an output array:
$assoc_array = array(
'edible_fruit' => 'apple',
'animal' => 'cat',
'edible_veg' => 'pumpkin',
'number' => '23',
'city' => 'Cape Town',
'edible_berry' => 'blueberry',
'color' => 'blue'
);
Would this work?
$result = array();
foreach ($assoc_array as $key => $value) {
if (substr($key, 0, 7) == "edible_") {
array_push($result, $value);
}
}
print_r($result);
Second:
How would I remove "edible_" from the output array's keys? With this second bit I have no idea where to even begin!
Third:
I've managed to figure out the above with all your help, thank you! Now I just need to find out how I would print each element on a new line with a date & timestamp at the end of each line? I've got this (doesn't seem to be working):
while (list($key, $value) = each($output)) {
print_r("$key => $value" . date("y/m/d G.i:s", time()) . "<br>");
}
First of your code will work.
To remove edible_ from the key you could use explode() -
$keyParts = explode('_', $key);
$newKey = $keyParts[1];
You will have to add the new keys to the array, which you're not doing now.
foreach ($assoc_array as $key => $value) {
if (substr($key, 0, 7) == "edible_") {
$keyParts = explode('_', $key);
$newKey = $keyParts[1];
$result[$newKey] = $value;
}
}
This would be my approach:
foreach($assoc_array as $key => $value) {
if(preg_match("/^edible_/",$key)) {
$result[preg_replace("/^edible_/","",$key)] = $value;
}
}
use preg_match to check if the key starts with what you are looking for and use preg_replace to remove the string from the beginning (^) of the key :)
Input ($assoc_array):
Array
(
[edible_fruit] => apple
[animal] => cat
[edible_veg] => pumpkin
[number] => 23
[city] => Cape Town
[edible_berry] => blueberry
[color] => blue
)
Output ($result):
Array
(
[fruit] => apple
[veg] => pumpkin
[berry] => blueberry
)
First: yes, that would work, however I would rewrite it a bit:
foreach ($assoc_array as $key => $value) {
if (strpos($key, 'edible_') === 0) {
$result[] = $value;
}
}
Regarding Second: You are asking how to remove the key from the output array. However you did not even push the key into the output array, you only pushed the value. If you'd like to also push the key, you should do it like this:
$result[$key] = $value;
But since you haven't done that, there's no need to remove the key.
If you however meant removing the edible_ part of the key from the $assoc_array, you'd just need to add a line to the loop and pass the key by reference by adding a &:
foreach ($assoc_array as &$key => $value) {
if (strpos($key, 'edible_') === 0) {
$key = str_replace('edible_', '', $key)
$result[] = $value;
}
}
Edit: As OP told me in comments, she wants to push the key without the edible part. So just do it like this:
foreach ($assoc_array as $key => $value) {
if (strpos($key, 'edible_') === 0) {
$key = str_replace('edible_', '', $key)
$result[$key] = $value;
}
}
This should work for you:
First I remove all elements, which doesn't have edible_ at the start of the key with array_diff_ukey(). After this I simply array_combine() the elements with they keys, where I remove the prefix with array_map() and substr().
<?php
$assoc_array = array('edible_fruit'=>'apple', 'animal'=>'cat', 'edible_veg'=>'pumpkin', 'number'=>'23', 'city'=>'Cape Town', 'edible_berry'=>'blueberry', 'color'=>'blue');
//remove elemnts
$result = array_diff_ukey($assoc_array, ["edible_" => ""], function($k1, $k2){
return substr($k1, 0, 7) == $k2;
});
//change keys
$result = array_combine(
array_map(function($v){
return substr($v, 7);
}, array_keys($result)),
$result);
print_r($result);
?>
output:
Array ( [fruit] => apple [veg] => pumpkin [berry] => blueberry )
You can loop through the array and search if the key has the string that you can eliminate and make your $newArray
<?php
$assoc_array = array('edible_fruit'=>'apple', 'animal'=>'cat', 'edible_veg'=>'pumpkin', 'number'=>'23', 'city'=>'Cape Town', 'edible_berry'=>'blueberry', 'color'=>'blue');
$search = 'edible_';
$newArray = array();
#First and Second Step
foreach($assoc_array as $key => $value) {
if(strpos($key, "edible_") === 0) {
$newArray[substr($key, 7)] = $value;
}
}
print_r($newArray);
echo "<br>\n";
#Third Step
foreach($newArray as $key => $value) {
echo "$key => $value " . date("y/m/d G.i:s", time()) . "<br>\n";
}
Output:
#First and Second Step
Array ( [fruit] => apple [veg] => pumpkin [berry] => blueberry )
#Third Step
fruit => apple 15/04/10 3.02:16
veg => pumpkin 15/04/10 3.02:16
berry => blueberry 15/04/10 3.02:16

Is there are way to start with a specific value in foreach loop of PHP?

Let say I have an array as follows:
$my_array = array(
"fruit1" => "apple",
"fruit2" => "orange",
"notfruit" => "hamburger",
"fruit3" => "banana"
)
Is there a way I can choose to start with $my_array['notfruit'] in an foreach loop of PHP? I don't care the sequence except the first one.
Currently I can think of copying the whole piece of code once and change it specifically for $my_array['notfruit'], then unset it from the array to use foreach loop to go through the remaining. i.e.
echo $my_array['notfruit']."is not fruit. Who put that in the array?";
unset ($my_array['notfruit']);
foreach ($my_array as $values) {
echo $values." is fruit. I love fruit so I like ".$values;
}
It works but it sounds stupid, and can cause problem if the content in the foreach loop is long.
You can filter out any element with a key that doesn't begin with fruit pretty easily
$fruits = array_filter(
$my_array,
function ($key) {
return fnmatch('fruit*', $key);
},
ARRAY_FILTER_USE_KEY
);
var_dump($fruits);
though using array_filter() with the keys like this does require PHP >= 5.6
EDIT
For earlier versions of PHP, you can swap the keys/values before filtering; then flip them again afterwards
$fruits = array_flip(
array_filter(
array_flip($my_array),
function ($value) {
return fnmatch('fruit*', $value);
}
)
);
var_dump($fruits);
Short answer, no.
You can, however pull whatever functionality you intended to have in the foreach into a funcion, then call the funcion specifically for the notfruit value, then run the foreach.
function foo($val) {
// do stuff with $val
}
$my_array = array(
"fruit1" => "apple",
"fruit2" => "orange",
"notfruit" => "hamburger",
"fruit3" => "banana"
)
foo($my_array['nofriut']);
unset($my_array['nofruit']);
foreach($my_array as $val) {
foo($val);
}
EDIT
Or if your case is as simple as your updated question, simply check if the key is nofruit
foreach($my_array as $key => $val) {
if($key === "nofruit") {
echo "$val is not fruit. Who put that in the array?";
} else {
echo "$val is fruit. I love fruit so I like $val";
}
}
You can use addition in arrays, which is more performant than array_unshift.
So unset it, and then add it back:
unset($my_array['notfruit']);
$my_array = array('notfruit' => 'hamburger') + $my_array;
var_dump($my_array);
Or if you want to use a variable:
$keyToMove = 'notfruit';
$val = $my_array[$keyToMove];
unset($my_array[$keyToMove]);
$newArray = array($keyToMove => $val) + $my_array;
var_dump($newArray);
Obviously you can put this all in a loop, applying it to any that you need to move.
Try this..
<?php
$my_array = array(
"fruit1" => "apple",
"fruit2" => "orange",
"notfruit" => "hamburger",
"fruit3" => "banana"
);
$new_value['notfruit'] = $my_array['notfruit'];
unset($my_array['notfruit']);
$newarray=array_merge($new_value,$my_array);
print_r($newarray);
?>
Result:Array ( [notfruit] => hamburger [fruit1] => apple [fruit2] => orange [fruit3] => banana )
There is too many options.
1 . Using array_merge or array_replace (i think that it is the simplest way)
$my_array = array_merge(['notfruit' => null], $my_array);
// $my_array = array_replace(['notfruit' => null], $my_array);
foreach ($my_array as $key => $value) {
var_dump($key, $value);
}
2 . Using generators.
$my_array = array(
"fruit1" => "apple",
"fruit2" => "orange",
"notfruit" => "hamburger",
"fruit3" => "banana"
);
$generator = function($my_array){
yield 'notfruit'=>$my_array['notfruit'];
unset($my_array['notfruit']);
foreach($my_array as $key => $value)
yield $key => $value;
};
foreach ($generator($my_array) as $key=>$value){
var_dump($key, $value);
}
3 . Readding value
$no_fruit = $my_array['nofruit'];
unset($my_array['nofruit']);
$my_array['nofruit'] = $no_fruit;
$my_array = array_reverse($my_array, true);
foreach ($my_array as $key=>$value){
var_dump($key, $value);
}
4 . Using infinitive iterator
$infinate = new InfiniteIterator(new ArrayIterator($my_array));
$limit_iterator = new LimitIterator(
$infinate,
array_search('notfruit', array_keys($my_array)), // position of desired key
count($my_array));
foreach ($limit_iterator as $key => $value) {
var_dump($key, $value);
}
$no_fruit = $my_array['nofruit']; // grab the value
unset($my_array['nofruit']); // remove value from array
array_unshift($my_array, $no_fruit); // add value at the beginning
or
$no_fruit = $my_array['nofruit']; // grab the value
unset($my_array['nofruit']); // remove value from array
$my_array = array('nofruit' => $no_fruit ) + $my_array; // add value at the beginning

Retrieve array key passed on value PHP

I have the following array
$group= array(
[0] => 'apple',
[1] => 'orange',
[2] => 'gorilla'
);
I run the array group through an for each function and when the loop hits values of gorilla I want it to spit out the index of gorilla
foreach ($group as $key) {
if ($key == gorilla){
echo //<------ the index of gorilla
}
}
You can use array_search function to get the key for specified value:
$key = array_search('gorilla', $group);
foreach( $group as $index => $value) {
if ($value == "gorilla")
{
echo "The index is: $index";
}
}
array_search — Searches the array for a given value and returns the corresponding key if successful
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
foreach($group as $key => $value) {
if ($value=='gorilla') {
echo $key;
}
}
The foreach($c as $k => $v) syntax is similar to the foreach($c as $v) syntax, but it puts the corresponding keys/indices in $k (or whatever variable is placed there) for each value $v in the collection.
However, if you're just looking for the index of a single value, array_search() may be simpler. If you're looking for indices for many values, stick with the foreach.
Try this:
foreach ($group as $key => $value)
{
echo "$key points to $value";
}
foreach documentation on php.net

Categories