2

I have this array written below, and I know it isnt pretty, sorry. I come to this array structure as it is the only way I could think of when dealing with my post request.

$_POST = array("person" => array(
                                 [1] => array("id" => 1, "name" => "bob"), 
                                 [2] => array("id" => 2, "name" => "jim")
                                )
               );

I want to be able to pick "name" from certain "id", so below code is what I came up with. In the example below, if person["id"] is equal to 1, retrieve its "name" which is "bob".

foreach ($_POST as $dataSet) {
    foreach ($dataSet as $person) {
        foreach ($person as $field => $value) {
            if ($person["id"] == 1) {
                echo $person["name"];
            }
        }
    }
}

The problem I am having is as I execute the code. the result is bobbob,

it seems like the code looped the if statement twice (same as the number of elements in the person array). I know if I put break into the code, then it will solve it, but anyone know why it looped twice? Maybe this will deepen my foreach and array understanding.

Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
Salam.MSaif
  • 209
  • 3
  • 10

5 Answers5

2

There is no need to have third nested loop. Hope this one will be helpful.

Problem: In the third loop you were iterating over Persons: array("id" => 1, "name" => "bob") which have two keys. and you are checking only single static key $person["id"], that's why it was printing twice.

Solution 1:

Try this code snippet here

<?php

ini_set('display_errors', 1);

$POSTData = array("person" => array(
        1 => array("id" => 1, "name" => "bob"),
        2 => array("id" => 2, "name" => "jim")
    )
);
foreach ($POSTData as $dataSet)
{
    foreach ($dataSet as $person)
    {
        if ($person["id"] == 1)
        {
            echo $person["name"];
        }
    }
}

Solution 2:

Alternatively you can try this single line solution.

Try this code snippet here

 echo array_column($POSTData["person"],"name","id")[1];//here 1 is the `id` you want.
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
2

No need of third foreach

 <?php
   $mainArr = array("person" => array(
                        1 => array("id" => 1, "name" => "bob"), 
                        2 => array("id" => 2, "name" => "jim")
                           )
                   );
   foreach ($mainArr as $dataSet) {
       foreach ($dataSet as $person) {
         if ($person["id"] == 1) {
             echo $person["name"];
             break;
         }
       }
   }

   ?>

Live demo : https://eval.in/855386

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
2

You must have seen the other answers, and they have already said that you dont need the 3rd loop. but still if you want to keep the third loop. you can use this code.

foreach ($_POST as $dataSet) {

    foreach ($dataSet as $person) {

        foreach ($person as $field => $value) {

            if($value == 1){
                echo $person['name'];
            }

        }

    }

}
Punit Gajjar
  • 4,937
  • 7
  • 35
  • 70
2

Although it's unclear why you need to do a POST in this fashion, here's how to get "bob" only once:

<?php

$_POST = array("person" => array(
                                 1 => array("id" => 1, "name" => "bob"), 
                                 2 => array("id" => 2, "name" => "jim")
                                )
               );



$arr = array_pop($_POST);

foreach($arr as $a) {
  if ($a["id"] == 1) {
    echo $a["name"];
  }
}

Array_pop() is useful for removing the first element of the array whose value is an array itself which looks like this:

array(2) {
  [1]=>
  array(2) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(3) "bob"
  }
  [2]=>
  array(2) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(3) "jim"
  }
}

When the if conditional evaluates as true which occurs only once then the name "bob" displays.

See live code.

Alternatively, you could use a couple of loops as follows:

foreach ($_POST["person"] as $data) {
    foreach ($data as $value) {
        if ( $value == 1) {
            echo $data["name"],"\n";
        }
    }
}

See demo

slevy1
  • 3,797
  • 2
  • 27
  • 33
1

As you mentioned, I want to be able to pick name from certain id, : No need of nested looping for that. You can do like this using array_column and array_search :

$data = array("person" => array(
        1 => array("id" => 1, "name" => "bob"),
        2 => array("id" => 2, "name" => "jim")
    )
);

// 1 is id you want to search for
$key = array_search(1, array_column($data['person'], 'id'));
echo $data['person'][$key + 1]['name']; // $key + 1 as you have started array with 1

Output:

bob

with foreach:

foreach ($data as $dataValue) {
    foreach ($dataValue as $person) {
        if ($person['id'] === 1) {
            echo $person["name"];
        }
    }
}
Jigar Shah
  • 6,143
  • 2
  • 28
  • 41