Echo out key and value from array - php

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

Related

Show All Data list of multidimensional array Using Foreach Loop

Here is The My Array Code...
$data = array(
'data_1',
'data_2',
'data_3',
'data_4',
'data_5' => array(
'data_5_1',
'data_5_2'
)
);
i Want to Ountput Like The : -
data_1
data_2
data_3
data_4
data_5
data_5_1
data_5_2
Here is My Code I try to Self But I Show Error
foreach($data as $da){
echo $da."<br>";
}
Error Found Like This
data_1
data_2
data_3
data_4
Notice: Array to string conversion in filename.php on line 3
Array
Please Fix this problem & Use echo not print_r
This is best achieved with a recursive function so that you can deal with any level of nested arrays:
function display_list($array) {
foreach ($array as $k => $v) {
if (is_array($v)) {
echo "$k\n";
display_list($v);
}
else {
echo "$v\n";
}
}
}
display_list($data);
Output:
data_1
data_2
data_3
data_4
data_5
data_5_1
data_5_2
Demo on 3v4l.org
You could use iterators:
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($data)) as $item)
echo "$item<br>", PHP_EOL;
As asked in comments, if you want either the key or value depending on type, you can use the flag SELF_FIRST and the ternary operator:
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($data), RecursiveIteratorIterator::SELF_FIRST) as $key => $item)
echo (is_scalar($item) ? $item : $key) . '<br>', PHP_EOL;
foreach ($data as $val) {
if(is_array($val)){
foreach ($val as $row) {
echo "<br> ".$row;
}
}
else{
echo "<br>".$val;
}
}

modify key in a foreach loop php

I want to change the value of the $key because I have array_splice inside the loop which change the position of my values so - it mess up the value I need in a specific place.
I tried $key-- but it doesn't work.
for example when I print the $key after I do echo $key it's fine but when I echo $key just after the foreach loop I get the worng value.
Any ideas?
foreach ($cut as $key => $value) {
echo "foreach key:".$key."<br>";
if(in_array($value,$operators))
{
if($value == '||')
{
echo "found || in position:".$key."<br>";
if(($key+1<sizeof($cut)))
{
$multi = new multi;
echo "<br>"."key-1: ";
print_r($cut[$key-1]);
echo"<br>";
echo "<br>"."key+1: ";
print_r($cut[$key+1]);
echo"<br>";
$res = $multi->orex($cut[$key-1],$cut[$key+1],$numString);
$cut[$key-1]= $res;
array_splice($cut,$key,1);
array_splice($cut,$key,1);
$key--; //here trying to change the key
echo "new string:";
print_r($cut);
echo "<br>";
echo "key:".$key."<br>";
}
}
}
}
Updated
I don't think it is a good idea to change the array itself inside the foreach loop. So please crete another array and fill data into it, which will be your result array. This method works well when your array data is not big, in other words, most situations.
Origin
I don't know what do you mean. Let me give it a guess...
You want:
foreach($arr as $key=>$val){
$newkey = /* what new key do you want? */
$arr[$newkey] = $arr[$key];
unset($arr[$key]);
}

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) {

How to echo out the values of this array?

How to echo out the values individually of this array?
Array ( [0] => 20120514 [1] => My Event 3 )
so
echo $value[0]; etc
I have this so far:
foreach (json_decode($json_data_string, true) as $item) {
$eventDate = trim($item['date']);
// positive limit
$myarray = (explode(',', $eventDate, 2));
foreach ($myarray as $value) {
echo $value;
}
This echo's out the whole string no as an array. and if i do this?
echo $value[0};
Then I only get 2 characters of it??
The print_r :
Array ( [0] => 20120430 [1] => My Event 1 )
foreach ($array as $key => $val) {
echo $val;
}
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
you need the set key and value in foreach loop for that:
foreach($item AS $key -> $value) {
echo $value;
}
this should do the trick :)
The problem here is in your explode statement
//$item['date'] presumably = 20120514. Do a print of this
$eventDate = trim($item['date']);
//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));
//$myarray is currently = to '20'
foreach ($myarray as $value) {
//Now you are iterating through a string
echo $value;
}
Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.
var_dump($value)
it solved my problem, hope yours too.

Traverse $_POST Array to show field Names

Is there a way to traverse an array such as $_POST to see the field names and not just the values. To see the values I do something like this.
foreach ($_POST as $value){
echo $value;
}
This will show me the values - but I would like to also display the names in that array. If my $_POST value was something like $_POST['something'] and it stored 55; I want to output "something".
I have a few select fields that I need this for.
You mean like this?
foreach ( $_POST as $key => $value )
{
echo "$key : $value <br>";
}
you can also use array_keys if you just want an array of the keys to iterate over.
You can also use array_walk if you want to use a callback to iterate:
function test_walk( &$value, $key )
{
...do stuff...
}
array_walk( $arr, 'test_walk' );
foreach ($_POST as $key => $value) {
echo $key; // Field name
}
Or use array_keys to fetch all the keys from an array.
foreach ($_POST as $key => $value){
echo $key.': '.$value.'<br />';
}
If you just want the keys:
foreach (array_keys($_POST) as $key)
{
echo $key;
}
Or...
foreach ($_POST as $key => $value)
{
echo $key;
}
If you want both keys and values:
foreach ($_POST as $key => $value)
{
echo $key, ': ', $value;
}
For just the keys:
$array = array_keys($_POST);
Output them with:
var_dump($array);
-or-
print_r($array);

Categories