How to get the current element count of an associative array? - php

Say I have this array
$array = array('pen' => 'blue', 'paper' => 'red', 'ink' => 'white');
When I loop through it
$string = '';
foreach ($array AS $key=>$value) {
$string .= $key . ' = ' . $value;
}
I want to get the "line number" of the element the loop is currently on.
If the loop is on "pen" I would get 1.
If the loop is on "paper" I would get 2.
If the loop is on "ink" I would get 3.
Is there an array command for this?

No. You will have to increment an index counter manually:
$string = '';
$index = 0;
foreach ($array as $key=>$value) {
$string .= ++$index . ") ". $key . ' = ' . $value;
}

Use array_values() function to extract values from array. It indexes array numerically and $key will be the index of value in loop.
$array = array('pen' => 'blue', 'paper' => 'red', 'ink' => 'white');
$array = array_values($array);
$string = '';
foreach ($array as $key => $value) {
$string .= $key + 1 . ' = ' . $value;
}

$i = 0;
foreach ($array as $key=>$value) { // For each element of the array
print("Current non-associative index: ".$i."<br />\n"); // Output the current index
$i++; // Increment $i by 1
}
Hope that helps.

Related

Create parent child from flat array php

Hello i have some simple array and want build child and parent.
$arr = array( 'a', 'b', 'c' );
function fre( $arr ) {
$i = 0;
foreach ( $arr as $key => $value ) {
echo '-' . $arr[$i];
$i++;
}
}
echo fre($arr);
I want final result like this:
a
-b
--c
Thank you.
You can achieve this with a simple cycle:
$prefix = "";
foreach ($arr as $value) {
echo $prefix.$value."\n";
$prefix .= "-";
}

How can i get sum of the values of an array where array index value starts with same value?

Here are my two arrays.
This array is $assesment I have tried the code given below and got $cat_array.
foreach($assesment as $k => $v){
$k2 = explode("_",$k);
/* echo "cat : ".$cat = $k2[0] ."-". $v;
echo "<br>";
echo "Que : ".$que = $k2[1]."-". $v;
echo "<br>"; */
$cat_array[] = $k2[0]."-".$v;
}
print_r($cat_array);
Just update your loop like as
$cat_array = array();
foreach($assesment as $k => $v){
$k2 = explode("_",$k);
if(isset($cat_array[$k2[0]])){
$cat_array[$k2[0]] += $v;
}else{
$cat_array[$k2[0]] = $v;
}
}

Get value separated by comma WordPress

How to get a value separated with comma. I used explode for it. This is what I've tried.
$get_item_desc = get_post_meta ($post->ID, 'item_description', true);
$arr = explode(",", $get_item_desc);
$item_string = '';
foreach($arr as $val){
echo $get_items = $item_string.trim($val).' ';
}
Sample Input:
Item 1, Item 2, Item 3
Sample Output:
DESC-1: Item 1
DESC-2: Item 2
DESC-3: Item 3
Based on your sample input/output, you can use:
$get_item_desc = get_post_meta($post->ID, 'item_description', true);
$arr = explode(',', $get_item_desc);
$i = 1;
foreach($arr as $val){
echo 'DESC-' . $i . ': ' . trim($val) . ' ';
$i++;
}

writing out checkbox list to string array for json php

I want to be able to write is a string that is an array which is going to be stored in a jason string in a data base. My code iterates over the checkboxes but I want to be able todo is test if the $input name is "interests"
<input type="checkbox" name="interests[]" value="dvd" />` <-- checkbox lists
the other thing which I can't get is to put quotes around each $value like e.g "dvd", "computers"
$interests = '[';
$count = 1;
$counter = count($_POST["interests"]);
foreach($_POST as $checkbox => $input) {
if(is_array($input)) {
// test here is input is "interests"
foreach($input as $index => $value) {
$interests .= /*quote here*/ $value /*quote here*/ .= ($count < $counter) ? ',' : '';
$count += 1;
}
}
}
$interests .= ']';
echo $interests;
interests is suppose to write out ["dvd", "computers", "hard drives"]
but it only writes out [dvd, computers, hard drives]
$_POST["interests"] = array("dvd", "computers", "hard drives");
$interests = '["' . implode('","', $_POST["interests"]) . '"]';
echo $interests;
See it in action
Use json_encode() instead of manually creating the JSON:
echo json_encode($_POST['interests']);
Outputs
["dvd","tv","radio"]
Try this,
$interests = '';
$count = 1;
$counter = count($_POST["interests"]);
foreach($_POST as $checkbox => $input) {
if(is_array($input)) {
// test here is input is "interests"
foreach($input as $index => $value) {
$interests .= $value .= ($count < $counter) ? ',' : '';
$count += 1;
}
}
}
$interests = json_encode($interests);
echo $interests;

To get the multi dimention array values in php

I have a multi-dimension array in php like this
$shop = array(
array("name","point","number"),
array('Ranjit', 1.25 , 15),
array('Pitabas', 0.75 , 25),
array('Khela', 1.15 , 7)
);
Now I have to show the output like this
name-> ranjit
Point-> 1.25
number->15
name->Pitabas
Point->0.75
number->25
name->Khela
Point->1.15
number->7
I am trying for loop, but I could get the result in nested forloop. Please help me to get the answer.
My solution:
$headings = array_shift($shop);
foreach ($shop as $item) {
foreach ($item as $key => $value) {
echo $headings[$key], '=>', $value;
}
}
Here's a simple loop: Observe that we skip the first element of the outer array, which is deemed to contain the headers:
for ($i = 1; $i != count($shop); ++$i)
{
print $shop[0][0] . ": ". $shop[$i][0] . "\n";
print $shop[0][1] . ": ". $shop[$i][1] . "\n";
print $shop[0][2] . ": ". $shop[$i][2] . "\n";
}
You know the first row will be the titles, so store them separately:
$titles = $shop[0];
That will give you
$titles = array('name', 'point', 'number');
Then loop through your array:
foreach ($shop as $index => $row) {
if ($index == 0)
continue;
foreach($row as $column => $item) {
echo $titles[$column] . " -> " . $item . "<br />";
}
}
This should give the desired output:
for($x = 1, $lim = sizeof($shop); $x < $lim; $x++)
{
echo $shop[0][0]."->".$shop[$x][0]."<br>";
echo $shop[0][1]."->".$shop[$x][1]."<br>";
echo $shop[0][2]."->".$shop[$x][2]."<br>";
}

Categories