Getting values from foreach - php

i have code which was written by a previous developer in our organization which says:
< ?php
foreach($response as $key => $value) {
?>
<tr>
<td><?php echo $key; ?></td>
<td><?php echo $value; ?></td>
</tr>
<?php
}
?>
i am very new to php and i dont know how to get values of $key[1]...$key[20] & $value[1]...$value[20] from this above code, since the above code writes 20 lines of values
I dont know if i am able to express this code problem in front of you correctly or not. sorry for my bad english.

As I understand your question, you want to have numerical indices..?
$key = array_keys($response);
$value = array_values($response);
Then you can use
$key[1]...$key[20] & $value[1]...$value[20]

< ?php
$keysarray = array();
$valuesarray = array();
int i = 0;
foreach($response as $key => $value) {
?>
<tr>
<td><?php $keysarray[i]= $key; echo $key; ?></td>
<td><?php $valuesarray[i]= $value; echo $value; ?></td>
</tr>
<?php
i++;
}
?>

The whole idea with a foreach loop is so you don't need to access the various indexes inside the array.
in your example, $response is an array.
during each iteration, the key/index of the array is assigned to $key and the value is assigned to $value.
eg.
$response = array('hello', 'goodbye');
// which is essentially the same as:
$response = array(0 => 'hello', 1 => 'goodbye');
during the first iteration of the foreach loop:
// first item in the array has an index of 0 and value of 'hello'
$key == 0;
$value == 'hello';
during pass two:
$key == 1;
$value == 'goodbye';

If your array $response is array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); then,
<?php
$response= array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($response as $key => $value) {
?>
<tr>
<td><?php echo $key; ?></td>
<td><?php echo $value; ?></td>
</tr>
<?php
}
Will Out put,
Peter 35
Ben 37
Joe 43
If $response is array("35","37","43");
then It will Out put,
0 35
1 37
2 43
In first case, Key will be as you given. It is known as Associative Arrays. Second, keys will be default from 0. It is Numeric arrays. No big deal.

Related

get the next key in array in php foreach loop

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.

How to add text to comma separated values in foreach loop?

I have data like in the image below, Im using foreach loop to show my data.
But I want to show my data like his, I want to add "IC" to all elements of Ids..
This is my current code..
<?php
foreach ($model as $mod) { ?>
<tr>
<td><?= $mod['discount']; ?></td>
<td><?= $mod['ids']; ?></td>
</tr>
<?php } ?>
What do i need to do to add "IC" to $mod['ids'] for each row to be IC10000, IC100000, IC10000, IC10000.
As i commented out to use- Explode the ID's by , then concatenate the IC and again putback
$model = array(array('discount' => '2000', 'ids' => '100,1000,1000,1000'), array('discount' => '2001', 'ids' => '100,1000,1000,1000'),array('discount' => '2002', 'ids' => '100,1000,1000,1000'));
foreach ($model as $k=> $mod) {
$mod_2 = preg_filter('/^/', 'IC', explode(',', $mod['ids']));
echo $mod['discount'].'-'.implode(', ', $mod_2).PHP_EOL;
}
Example: https://3v4l.org/5I3l0
Through foreach loop you can do it !
PHP
<?php
$ids = "100,200,300,400,500,600";
$ids_array = explode(",",$ids);
$new_ids = array();
foreach($ids_array as $values){
$new_ids[] = "IC".$values;
}
echo implode(",",$new_ids);
?>
OUTPUT
IC100,IC200,IC300,IC400,IC500,IC600

How to get position of a value in a php array

<?php
$arr1 = preg_split("/[;]+/", $data);
foreach ($arr1 as $arr1 => $value) {
echo '<td>';
echo $value;
echo '</td>';
if (key($value)==6)
{
echo '</tr>';
echo '<tr>';
}
}
?>
This is code I am using but the key function is not returning anything.
I want to get return the position of $value and want to excecute some code if it is divisible by 6.
How can I get the position of $value in $arr1?
You must use a different variable than $arr1 to store the key.
Use this instead, where $key will be the key:
<?php
$arr1 = preg_split("/[;]+/", $data);
foreach ($arr1 as $key => $value) {
echo '<td>';
echo $value;
echo '</td>';
if ($key==6)
{
echo '</tr>';
echo '<tr>';
}
}
?>
You can following example to get position of particular $value in array.
<?php
$value = 'green';
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key_of_particular_value = array_search($value, array);
//After perform above operation $key_of_particular_value = 2
//Below statement will check whether key is divided by 6 or not
if(($key_of_particular_value % 6) == 0)
{
//perform your operation
}
?>
To know more please refer following link-
http://php.net/manual/en/function.array-search.php
You have used same variable $arr1 for key and original array, try using another variable to get key(index)
foreach ($arr1 as $key => $value) {

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];
}

php foreach echo prints "Array" as value

Perhaps I'm simply having trouble understanding how php handles arrays.
I'm trying to print out an array using a foreach loop. All I can seem to get out of it is the word "Array".
<?php
$someArray[]=array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value;
?>
<br />
<?php
}
?>
This prints out this:
Array
I'm having trouble understanding why this would be the case. If I define an array up front like above, it'll print "Array". It almost seems like I have to manually define everything... which means I must be doing something wrong.
This works:
<?php
$someArray[0] = '1';
$someArray[1] = '2';
$someArray[2] = '3';
$someArray[3] = '4';
$someArray[4] = '5';
$someArray[5] = '6';
$someArray[6] = '7';
for($i=0; $i<7; $i++){
echo $someArray[$i]."<br />";
}
?>
Why won't the foreach work?
here's a link to see it in action >> http://phpclass.hylianux.com/test.php
You haven't declared the array properly.
You have to remove the square brackets: [].
<?php
$someArray=array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value;
?> <br />
<?php
}
?>
Try:
<?php
$someArray = array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value . "<br />\n";
}
?>
Or:
<?php
$someArray = array(
0 => '1',
'a' => '2',
2 => '3'
);
foreach($someArray as $key => $val){
echo "Key: $key, Value: $val<br/>\n";
}
?>
actually, you're adding an array into another array.
$someArray[]=array('1','2','3','4','5','6','7');
the right way would be
$someArray=array('1','2','3','4','5','6','7');

Categories