get the next key in array in php foreach loop - php

I have a select box and wanting to get the key of the next value in array to go with the option here is my code
<select>
<?php foreach ($make as $key => $make):?>
<option value="<?php echo next($key);//not correct ?> - <?php echo $key; ?>"> <?php echo $make; ?></option>
<?php endforeach;
Here is the array
Array
(
[0] => Brand
[1] => Alfa Romeo
[123] => Alpina
[142] => Aston Martin
[152] => Audi
[619] => Bentley
[640] => BMW
[1122] => Buick
)

This will work with an associative array as well as numerically indexed:
<?php foreach ($make as $key => $value):?>
<?php next($make); ?>
<option value="<?php echo key($make); ?> - <?php echo $key; ?>"> <?php echo $value; ?></option>
<?php endforeach; ?>
Note, it's confusing and probably a bad idea to use the same variable name for iterating as the array. so instead of foreach ($make as $key => $make) I did foreach ($make as $key => $value) here.
The code above simply advances the pointer on the array and then gets the key for your option value using key(). Since there is no next key on the final array element, the value will be empty.

You can resolve your issue with a lot of solution, but if you have an assoiatve array or none order array or not numirc, you can use this:
<?php
$array = ["a" => 1, "b" => 2, "c" => 3, 1 => "aa"];
next($array);
$key = key($array);
echo $key;
prev($array);
$key = key($array);
echo $key;
Else, if array is ordered and numeric you can use $key + 1;

Simple way to get key of next element is to use array_search of next element of array e.g.
<?php foreach ($makers as $key => $make):?>
<option value="<?php echo array_search( next($makers), $makers );"> <?php echo $make; ?></option>
<?php endforeach;
Hope this helps.

try this function. it finds current key of given value in the array, and from that found key's position, you can get next/previous key with $increment
Ex: when $increment=1, it finds next key
when $increment=2, it finds 2 next key
when $increment=-1, it finds 1 previous key, and so on.
function sov_find_key($findvalue, $array, $increment) {
reset($array);
$key = array_search($findvalue, $array);
if ($key === false || $key === 0){
return false;
}
if ($increment === 0){
return $key;
}
$isNegative = $increment < 0 ? true:false;
$increment = abs($increment);
while(key($array) !== $key) {
next($array);
}
$x=0;
while($x < $increment) {
if( $isNegative ){
prev($array);
} else {
next($array);
}
$x++;
}
return key($array);
}
DEMO: https://3v4l.org/CSSmR

<select>
<?php
foreach ($make as $key => $make):
?>
<option value="<?php echo $key + 1; ?> - <?php echo $key; ?>">
<?php echo $make;
?>
</option>
<?php
endforeach;
Just increment the $key by 1, and you will have the next array element if the keys are in order and are numeric.

Related

Looping the array in select

I have this kind of array shown in Picture. How can i insert the values in the select option as
<option value="7">7</option>
<option value="13000">13000</option>
<option value="19AAAAA">19AAAAA</option>
<option value="sdsdas">sdsdas</option>
<option value="dasdasdasd">dasdasdasd</option>
Simply flatten the multi-dimensional array, and then loop through it.
Suppose $arr in your original multi-dimensional array
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach($it as $value){
?>
<option value="<?php echo $value; ?>"><?php echo $value; ?></option>
<?php
}
Here are the relevant references:
http://php.net/manual/en/class.recursiveiteratoriterator.php
http://php.net/manual/en/class.recursivearrayiterator.php
<?php
foreach($arr as $val){
foreach($val as $val2){
foreach($val2 as $val3){ ?>
<option value="<?php echo $val3;?>"><?php echo $val3 ;?></option><?php
}
}
}
?>
You need to flat array. You can do it with recursive function. Here you have general function for that.
/**
* Get multilevel array convert to single-level array
* #param $array
* #return array
*/
function getFlattened($array) {
$flattened = [];
foreach ($array as $flat) {
if (is_array($flat)) {
$flatArray = array_merge($flatArray, getFlattened($flat));
} else {
$flattened[] = $flat;
}
}
return $flattened;
}
Of course you can use that approach to recursively display select - not only to flat array.
<?php foreach($array as $inner): ?>
<?php foreach($inner as $innerTwo): ?>
<?php foreach($innerTwo as $item): ?>
<option value="<?= $item ?>"><?= $item ?></option>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endforeach; ?>
you may try this.
<?php
$input = Array(
Array
(
0 => 7,
1 => 13000
),
Array
(
0 => '19AAAAA',
1 => 'sdsdas'
)
);
$options = "";
$result = call_user_func_array("array_merge", $input);
for($i = 0;$i< count($result);$i++ ){
$options .="<option value='".$result[$i]."'>".$result[$i]."</option>";
}
echo $options;

How to compare key and value in more than two array?

I am comparing three arrays in nested foreach conditions. Following are the arrays
Array
(
[master/city] => City
[master/national_holiday] => National Holiday
[master/operator_comments] => Operator Comments
[master/sensors] => Sensors
[master/modbus] => Modbus
[master/manufacturers] => Manufacturers
[master/make_model] => Make Model
[master/dispatch_vendors] => Dispatch Vendors
)
Array
(
[1] => View
[2] => Write
)
Array
(
[master/city] => 1
[master/national_holiday] => 2
[master/operator_comments] => 1
[master/sensors] => 2
[master/modbus] => 1
[master/manufacturers] => 2
[master/make_model] => 1
)
Now the scenario is as follows:-
My first foreach iteartes first array
Then in the same foreach i m using second foreach which itrates second array
again in second foreach i m using third foreach to iterate third array
In third foreach , i m comparing key of first array with the key of second array and comparing value of second array with key of third array
If above condition is satisfied then in my dropdown the specific option will append selected Like <option value="1" selected="">View</option>
I am using following code
<?php
$first_array = first_array();
$i = 1;
foreach($first_array as $k => $val) {
?>
<tr>
<td>{{ $i }}</td>
<td class="mailbox-name">{{ $val }}</td>
<td><?php $second_array = second_array(); ?>
<select class="form-control master-menu" name="master_menu[{{$k}}]">
<option value="">Select Role</option>
<?php
foreach ($second_array as $key => $value) {
foreach ($third_array as $mkey => $mval) {
?>
<option value="<?php echo $key; ?>"
<?php if (($mkey == $k) && ($mval == $key)) { echo "selected"; } ?>><?php echo $value; ?></option>
<?php } } ?>
</select>
</td>
</tr>
<?php $i++; } ?>
I am using above code and getting issue that in second array there two values and in third array five values so in my dropdown count of option are ten insted of two.
This is my output.
Please suggest me.
Maybe something like this? I have simplified the process to demonstrate what is happening. I have also added the correct select values:
foreach ($first_array as $key => $value) {
?>
<p><?php echo $value; ?></p>
<?php foreach ($second_array as $second_key => $second_value) { ?>
<?php if ($key == $second_key) { ?>
<select>
<?php foreach ($third_array as $third_key => $third_value) { ?>
<option <?php echo ($third_key == $second_value ? 'selected=selected' : null); ?>><?php echo $third_value; ?></option>
<?php } ?>
</select>
<?php } else { ?>
<select>
<?php foreach ($third_array as $third_key => $third_value) { ?>
<option ><?php echo $third_value; ?></option>
<?php } ?>
</select>
<?php } ?>
<?php } ?>
<?php
}
For example you may try this code
foreach ($tmparray as $innerarray) {
//check type
if (is_array($innerarray)) {
//echo through inner loop
foreach ($innerarray as $value) {
echo $value;
}
} else {
//one,two,three
echo $innerarray;
}
}

Echo selected values from an associate array

i dont want to echo the last two values in an associative array, couldn's figure it out, please help.
foreach($_POST as $key => $value){
echo $value;
}
This echoes all the values, i want to echo all but the last 2.
Just count the loops and dont print the value in the last two loops.
$i = 0;
foreach($_POST as $key => $value) {
$i++;
if($i != count($_POST) && $i != count($_POST)-1) {
echo $value;
}
}
It should work to slice the array before you loop it.
<?php
$newArray = array_slice( $_POST, 0, count($_POST)-2);
foreach( $newArray AS $key => $value ) {
echo $value;
}
If you want to keep your $key value, then set the 4th parameter to true to "preserve keys":
http://php.net/manual/en/function.array-slice.php
Maybe this is just an exercise, but I do want to note, in addition, that relying on the exact order of your POST'd elements sounds like a bad design idea that could lead to future problems.
I'd rather do this:
$a = array('a' => 'q','s' => 'w','d' => 'e','f' => 'r');
$arr_count = count($a) - 2;
$i = 1;
foreach($a as $k => $val){
echo $k.' - '.$val.PHP_EOL;
if ($i == $arr_count) break;
$i++;
}
Another alternative solution:
<?php
$tot=count($_POST)-2;
while ($tot--) {
// you can also retrieve the key using key($_POST);
echo current($_POST);
next($_POST);
}

Echo out key and value from array

I have an array called $topProductIdResults and it looks like the following:
Array ( [11497522] => 2 )
The keys are prodcuct ID's and the value is the number of 5 star ratings that the product has recieved.
I want it to echo out this data using a loop. However I can't work our how to echo out both the key and value. Sometimes there will be several product ID's and number pairs in this array. Please let me know where I'm going wrong. My code so far is:
foreach ($topProductIdResults as $prod) {
echo $prod[0];
echo $prod[1];
}
which just echo's 22 at the moment. I want it to echo 11497522 2
foreach ($topProductIdResults as $key => $value) {
echo $key;
echo $value;
}
Try this :
foreach ($topProductIdResults as $key=>$prod) {
echo $key;
echo $prod;
}
Ref: http://php.net/manual/en/control-structures.foreach.php
If you just have a single dimensional array with key and value Array ( [11497522] => 2 ) , then you can use this :
$array = array(11497522=>2);
$key = key($array);
$value = $array[$key];
Use this
foreach ($topProductIdResults as $key => $value)
{
echo $key;
echo $value;
}
Try this
foreach ($topProductIdResults as $prodid => $prod) {
echo $prod[0];
echo $prod[1];
}

how do I echo out an array array using foreach?

i am trying to automate my navigation links. How do I automatically echo out foreach. I am getting undefined offset right now... And can I ignore the first item in the array (i.e. title)?
'control' => array( 0=>'Controls',
1=> array('Add school','add.school.php'),
2=> array('Add doctor','add.doctor.php'),
3=> array('Add playgroup','add.play.php'),
4=> array('Suggestions','suggestion.php'),
5=> array('List tutor service','list.tutor.php'),
6=> array('Create playgroup','create.play.php'),
7=> array('Dashboard', 'dashboard.php')
),
<?php
foreach ($nav['control'] as $value=>$key){
echo''.$key[1].'';
}
?>
Numeric arrays are indexed from 0, not 1. You want [1] and [0] respectively.
// for key => value is more nature.
foreach ($nav['control'] as $key => $value){
// should skip the first.
if ($key === 0) {
continue;
}
// array is 0 base indexed.
echo''.$value[0].'';
}
foreach ($nav['control'] as $value=>$key) {
echo''.$key[0].'';
}
a nested array requires nested loop.
foreach($array as $key => $value){
if($key != 0){
foreach($value as $k => $v){
if($k == 0){ $title = $v;}
if($k == 1){ $link = $v;}
}
//put code to run for each entry here (i.e. <div> tags, echo $title and $link)
}
my personal practice when i only use two fields is to push the first into the array['id'] and the second as the value i.e.
while($row_links = sth->fetch (PDO::FETCH_ASSOC)){
$array[$row_links['title']] = $row_links['link'];
}
then you can use
<?php foreach($array as $key => $value){ ?>
<?php echo $key; ?>
<?php } ?>

Categories