How to get last key with values from array of arrays? PHP - php

This is what i am currently using
<?php $sidebar = $this->data['sidebar'];
$lastKey = array_pop(array_keys($sidebar));
$sidebar = $this->data['sidebar'][$lastKey]; ?>
<?php foreach($sidebar as $key => $item) { ?>
<li id="<?php echo Sanitizer::escapeId( "pt-$key" ) ?>"<?php
if ($item['active']) { ?> class="active"<?php } ?>><?php echo htmlspecialchars($item['text']) ?></li>
<?php } ?>
This is what i get (http://pastebin.com/t6Y2ZtMF) when i print_r($sidebar);
I want to get the last Array which is Categories and turn it into links.
I am new to php, so my method could be wrong even though it works. I is there a right way to pull the Categories Array or the above code is good as it is?

$lastValue = end($array);
$lastKey = key($array); // current key, which is the last since you called end()
After update:
You don't seem to be needing the key, only the array:
<?php $lastSidebarValue = end($this->data['sidebar']); ?>
<?php foreach ($lastSidebarValue as $key => $item) : ?>
business as usual...
<?php endforeach; ?>
Since you know you want the key 'Categories' though (not the last key), this seems the most logical thing to do:
<?php foreach ($this->data['sidebar']['Categories'] as $key => $item) : ?>
business as usual...
<?php endforeach; ?>

I think the end() function would be a great solution: http://php.net/manual/en/function.end.php
It basically returns the value of the last element in the array being passed to it.
$sidebar = end($sidebar);

If you want to get a key/value pair without popping & pushing the array, set the internal cursor to the end of the array and then use list and each to get the key & value.
// set up your array however you had it
$array = ...;
// move the cursor to the end of the array
end($array);
// use list() and each() to extract your key/value pair
list($key,$val) = each($array);
// $key will now have the last key
// $val will have the last value

perhaps, end:
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry

You can use `end()` instead of `array_pop()`. But both works for the **last element** of the array. The only difference is `end()` **points out** the **last element** of the array without effecting it and `array_pop()` **pops** the element off the **end** of array.
Please go through the following links for detail information
end() | array_pop()

Related

PHP foreach insert array

I have an array of arrays, and I am trying to foreach loop through and insert new item into the sub arrays.
take a look below
$newarray = array(
array("id"=>1,"quantity"=>2),
array("id"=>1,"quantity"=>2),
array("id"=>1,"quantity"=>2),
);
foreach($newarray as $item){
$item["total"] = 9;
}
echo "<br>";
print_r($newarray);
The result just give me the original array without the new "total". Why ?
Because $item is not a reference of $newarray[$loop_index]:
foreach($newarray as $loop_index => $item){
$newarray[$loop_index]["total"] = 9;
}
The foreach() statement gives $item as an array: Not as the real value (consuming array). That meaning it can be read but not changed unless you then overwrite the consuming array.
You could use the for() and loop through like this: see demo.
Note: This goes all the way back to scopes, you should look into that.

Stripslashes() on array

I have some problems using stripslashes() on array.
Here is my array :
$tabRegion = array(
1=>"Alsace",
2=>"Aquitaine",
3=>"Auvergne",
4=>"Basse-Normandie",
5=>"Bourgogne",
6=>"Bretagne",
7=>"Centre",
8=>"Champagne-Ardenne",
9=>"Corse",
10=>"Franche-Comté",
(...)
21=>"Provence-Alpes-Côte d'Azur",
22=>"Rhône-Alpes",);
In order to stripslash, I have adapted this PHP code :
foreach ($tabRegion as $key=>$region) {
$tabRegion[$key] = stripslashes($region);
}
After in the file, I generate URL with it for example :
if (file_exists('../region/$tabRegion[$region]/$fonction/messages/$lecturefichier (...)
But the fact is that the last value of the array is always selected ("Rhône-Alpes") by the code... I don't know why.
Do you have an idea? :)
Thank you !
You are using foreach loop then you have to generate url in that loop.
In that loop you will get each region value
$tabRegion = array(
1=>"Alsace",
2=>"Aquitaine",
3=>"Auvergne",
4=>"Basse-Normandie",
5=>"Bourgogne",
6=>"Bretagne",
7=>"Centre",
8=>"Champagne-Ardenne",
9=>"Corse");
foreach ($tabRegion as $key=>$region)
{
$tabRegion[$key] = stripslashes($region);
print "<br>".$region;
}
Output will be :
Alsace
Aquitaine
Auvergne
Basse-Normandie
Bourgogne
Bretagne
Centre
Champagne-Ardenne
Corse
So that,you have to insert following line in that for loop :
if (file_exists('../region/$tabRegion[$region]/$fonction/messages/$lecturefichier (...)
You are using $region variable in foreach loop and you should know that it is treated like any other variable in your script. So for example:
$fruit = 'Banana';
foreach(array('Tomato', 'Orange') as $fruit) {
echo $fruit;
}
echo $fruit; // it will output 'Orange';

Getting key from array without looping when there is only one record

$array['2']['21'] = null;
I want to get 21 from array above without looping, is it possible? I want to do it for those arrays which have ONLY 1 record in them. Obviously I'll have to use loop for others.
foreach ($array['2'] as $key => $value)
{
echo $key;
//I know this does the job wondering if there is simple function
}
I looked at extract() but doesn't do my job.
try this :
$arr_keys = array_keys($array['2']);
echo "<pre>";
print_r($arr_keys);
Ref: http://php.net/manual/en/function.array-keys.php

Looking foward or back in a foreach loop

I am rendering navigation from a 2 dimensional array, using lists, as shown:
<ul> <li>parent
<ul> <li>level 1</li> <li>level 1
<ul> <li>level 3</li> </ul>
</li> </ul>
<li> </ul>
</li> </ul>
Anyway to close the <li> and </ul> correctly I find I need some data from the next array in the foreach sequence. How can I retrieve this?
Although I've had choppy results with them in the past you can use the below functions to move the current array pointer.
prev() - http://www.php.net/manual/en/function.prev.php
next() - http://www.php.net/manual/en/function.next.php
end() - http://www.php.net/manual/en/function.end.php
reset() - http://www.php.net/manual/en/function.reset.php
Hopefully that'll help.
Here's a solution:
$arr = array(1,2,3,4,5);
foreach ($arr as $foo) {
if (empty($isrewind)) {
reset($arr);
$isrewind = true;
}
echo "node: $foo\n";
$copy = $arr; // make a copy of the array
$next = next($copy);
echo "next: $next\n";
$copy = $arr; // make a copy of the array
$prev = prev($copy);
echo "prev: $prev\n";
next($arr); // don't forget to advance the pointer on the original array
}
I've demonstrated the prev bit just for the example. You can easily do that without prev() by saving the element at the end of each iteration.
The if empty bit resets the array pointer to the beginning, because foreach will advance the pointer once when it makes a copy of the array.
The above example yields:
node: 1
next: 2
prev:
node: 2
next: 3
prev: 1
node: 3
next: 4
prev: 2
node: 4
next: 5
prev: 3
node: 5
next:
prev: 4
If you have to do something like this though, there might be a better way just by rearranging your data structure (hard to tell without code).
IHMO it's not possible with a simple foreach loop on an array that has non-numeric indexes. But you can extend the SPL class CachingIterator to wrap your array in this. In your extended class you can implement methods to return the previous and next index/value without advancing the internal element pointer.
If you have an array with numeric indexes use a for loop instead of a foreach. You can then use $i+1 and $i-1 to look at different array indexes than the current index.
Not sure if this is what he asking for, but here's my shot
$list = array (
'Home page' => null,
'Articles' => array (
'Diving' => null,
'Skydiving' => null,
'Stackoverflowing' => null,
),
'Nobody cares' => array (
'Hey' => null,
'It is just a test' => null,
),
);
function render_menu ($list)
{
echo "<ul>\n";
foreach ($y = new RecursiveArrayIterator ($list, RecursiveIteratorIterator::SELF_FIRST) as $key => $item)
{
if ($y->hasChildren ())
{
echo "<li>$key\n";
render_menu ($item);
echo "</li>\n";
}
else
{
echo "<li>$key</li>\n";
}
}
echo "</ul>\n";
}
render_menu ($list);
Found the answer staring me in the face. Retrieved the arrays I need like this:
foreach ($tree as $key => $link) {
$level = $link['level'];
$next_key = $key+1;
$prev_key = $key-1;
$next_array = $tree[$next_key];
$prev_array = $tree[$prev_key];
And then I could test the level property (indicating deph inside the navigation tree) with a buch of if statements to correctly insert the closing markup.
Messy code and I'm not proud of it, but it works!
Quite angry with myself for not seeing it before.
I assume you are using php. I dont think it's possible, you must know the index of element and index the array. Sth like this:
$i=0;
foreach ($array as $element){
echo $element;
//do sth with $array[$i+1];
//do sth with $array[$i-1];
$i++;
}
Have no other clue

Outputting the count in a foreach function

I am working with SimplePie and I cannot figure out how to output the count, or the key values for the loop.
Shouldn't this
<?php foreach ($feed->get_items() as $item): ?>
<?php
$i = key($item);
echo $i;
?>
<?php endforeach; ?>
, or this
<?php foreach ($feed->get_items() as $item): ?>
<?php
$i = count($item);
echo $i;
?>
<?php endforeach; ?>
be outputting a unique number for each?
uniqid() Doesn't work in this case, because I am running the loop twice on the page and trying to match up one list of elements with another based on ID.
A single argument used with as is interpreted as a variable in which to store the value, not the key. If you want the key, you need to use => in a manner like the following:
foreach ($feed->get_items() as $key => $item):
echo $key;
endforeach
As a sidenote, you're using key() and count() on an item in the array, rather than the array as a whole, which is invalid. As far as I'm aware, there's no guarantee that key() will work as you expect even if applied to the whole array. It's meant for loops where you control the iteration, as with next.
To get the 'count' in a foreach you would need an extra variable. Getting the key is easy and the same if the array is indexed in order instead of associative. Here is an example including both:
$array = array(
'foo' => 'bar'
);
$i = 0;
foreach ($array as $key => $value)
{
/*
code where $i is the 'count' (index) and $key is the associative $key.
*/
/* $i == 0 */
/* $key == 'foo' */
/* $value == 'bar' */
$i++;
}
key($item) that you're using above doesn't work because you're trying to get the key of a value that no longer is associated with the original array.
count($item) is the count of a subarray $item.
you can use get_id() method
like :
foreach ($feed->get_items() as $item)
{
$prev_ids = array('guid1', 'guid2', 'guid3', 'guid4');
if (in_array($item->get_id(true), $prev_ids))
{
echo "This item is already stored.";
}
else
{
echo "This is a new item!";
}
}

Categories