This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Loop an array of array
So I know how to traverse an array of even key => value (associative), but I have a weird array where I need to walk through it and print out values:
$object_array = array(
'type' => 'I am type',
array(
'property' => 'value',
'property_2' => 'value_2'
)
);
What I thought I could do is:
foreach($object as $key=>$vlaue){
//what now?
}
So as you can see I am lost, how do I walk through the next array?
You can try:
function traverse($array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
traverse($array);
continue;
}
echo $value;
}
}
foreach($object as $key=>$value){
if( is_array($value) ) {
foreach($value as $key2=>$value2) {
//stuff happens
}
} else {
//other stuff
]
}
Try:
foreach($object_array as $value) {
if(!is_array($value))
echo $value;
else {
foreach($value as $m)
echo $m;
}
}
Manual for foreach
In your for loop you could do:
if(is_array($object[$key]))
//process inner array here
It depends on how deep your arrays go, if you have arrays of arrays of arrays...and so on, a different method would be better, but if you just have one level this is a pretty simple way of doing it.
Well, you could do something like this:
foreach($object_array as $key=>$value)
{
if(is_array($value) {
foreach($value as $k=>$v) {
echo $k." - ".$v;
}
} else {
echo $key." - ".$value;
}
}
An alternative with array_walk_recursive():
function mydebug($value, $key) {
echo $key . ' => ' . $value . PHP_EOL;
}
array_walk_recursive($object_array, 'mydebug');
Handy if you doing something simple with the values (e.g. just echo ing).
Related
its easy for sure..
i have code like this:
$indeks = 0;
foreach ($list as $k => $v)
{
$data['fname'] = $customer->firstname;
$data['lname'] = $customer->lastname;
$data['code'] = $code['code'];
$tablica[$indeks] = $data;
$indeks++;
and i want to read only 'code' value for each array.
i try:
foreach($tablica as $k => $v){
foreach ($v as $key => $value ) {
echo $value
}
}
but i get all arrays values.
when i try
foreach($tablica as $k => $v){
foreach ($v['code'] as $key => $value ) {
echo $value
}
}
i have nothing...
thx for help
You can use array_column function to get all values of column, for example:
foreach (array_column($tablica, 'code') as $value) {
echo $value;
}
I think a For loop should help
for($i=0;$i<count($tablica);$i++){
echo $tablica[$i]['code'];
}
or get all Codes into an Array
$code = array();
for($i=0;$i<count($tablica);$i++){
$code[$i] = $tablica[$i]['code'];
}
You don't need nested loops.
foreach ($tablica as $value) {
echo $value['code'];
}
DEMO
I want to use a multidimensional array in different functions.so i am making it as a global variable(array).i created a multidimensional array and made it as global to access in different function.now how can i get the values from it using foreach loop?
here is my code
$test=array(
array(
"input1"=>"v1",
"input2"=>"v2"),
array(
"input3"=>"v3",
"input4"=>"v4")
);
class testing
{
function testp()
{
global $test;
foreach($test as $key => $value)
{
echo $value;
}
var_dump($test);
echo is_array($test);
}
}
$obj = new testing();
$obj->testp();
i used is_array and var_dump to confirm whether its an array.
all are fine
and its shwoing Error suppression ignored. now how can i get the values from it?
It is array of arrays, what works for top order array, works further as well:
foreach($test as $key => $value)
{
foreach($value as $k => $v){
echo $v;
}
}
This will echo your values v1, v2, v3, v4 one after another.
More general answer:
public function visitArray($test)
{
foreach($test as $key=>$value)
{
if(is_array($value))
{
visitArray($value);
}
else
{
echo $value;
}
}
}
Edit
Don't know why you're looping over keys and values, if key isn't took into account
More easy & simple way to access array values within a array.
foreach($test as $array_value){
if(is_array($array_value)) {
foreach ($array_value as $value) {
echo $value.'<br>';
}
}
}
I want to know the correct code to detect only numerical $_POST fields coming from the form.
Please correct my code.
foreach ($_POST as $vals) {
if (is_numeric($vals)) {
if (is_numeric($vals[$i]) && ($vals[$i]!="0")) {
//do something
}
}
$_POST = array_filter($_POST, "is_numeric");
The above will remove all non-numeric array items.
foreach (array_filter($_POST, "is_numeric") as $key => $val)
{
// do something
echo "$key is equal to $val which is numeric.";
}
Update:
If you only want those like $_POST[1], $_POST[2], etc..
foreach ($_POST as $key => $vals){
if (is_numeric($key)){
//do something
}
}
try:
foreach ($_POST as $key => $vals){
//this is read: $_POST[$key]=$value
if (is_numeric($vals) && ($vals!="0")){
//do something
}
}
if(isset($_POST)){
foreach($_POST as $key => $value){
if(is_numeric($key)){
echo $value;
}
}
}
Compare the keys
Try this:
foreach ($_POST as $key => $val)
{
if (is_numeric($key))
{
// do something
}
}
The following code with isset() trying to work on an array is invalid.
if(isset($_POST)){ //isset() only works on variables and array elements.
foreach($_POST as $key => $value){
if(is_numeric($key)){
echo $value;
}
}
foreach ($_POST as $key => $val)
{
if (is_numeric($key))
{
// do something
}
}
Better, but now foreach will make a copy of $_POST and put in in memory for the duration of the loop (Programming PHP: Ch. 6, p. 128-129). I hope buffer overflows or out of memory errors don't jump up and bite you. :-)
Perhaps it would be wiser to determine some facts about $_POST with is_array(), empty(), count() and others before getting started, such as ...
if(is_array($_POST) && !empty($_POST))
{
if(count($_POST) === count($arrayOfExpectedControlNames))
{
//Where the the values for the $postKeys have already been validated some...
if(in_array($arrayOfExpectedControlNames, $postKeys))
{
foreach ($_POST as $key => $val) //If you insist on using foreach.
{
if (is_numeric($key))
{
// do something
}
else
{
//Alright, already. Enough!
}
}
}
else
{
//Someone is pulling your leg!
}
}
else
{
//Definitely a sham!
}
}
else
{
//It's a sham!
}
Still, the $val values need some validation, but I'm sure you are up on that.
I have following array construction: $array[$certain_key][some_text_value]
And in a while loop, I want to print the data from the array, where $certain_key is a specific value.
I know how to loop through multidimensional arrays, which is not the complete solution to this problem:
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}
I do not want to loop the whole array each time, but only when $certain_key is matched.
EDIT: to be more exact, this is what I'm trying to do:
$array[$array_key][some_text];
while reading from db {
//print array where a value returned from the db = $array_key
}
while ($row = fetch()) {
if (isset($array[$row['db_id']])) {
foreach ($array[$row['db_id']] as $some_text_value => $some_text_values_value) {
echo ...
}
}
}
foreach ($array as $certain_key => $value) {
if($certain_key == $row['db_id']) {
foreach ($value as $some_text_value) {
echo "$v2\n";
}
}
}
You mean like
foreach($array[$certain_key] as $k => $v)
{
do_stuff();
}
?
Maybe you're looking for array_key_exists? It works like this:
if(array_key_exists($certain_key, $array)) {
// do something
}
<?php
foreach ($a as $idx => $value) {
// replace [search_value] with whatever key you are looking for
if ('[search_value]' == $idx) {
// the key you are looking for is stored as $idx
// the row you are looking for is stored as $value
}
}
I iterate through an array of objects and want to delete one of the objects based on it's 'id' property, but my code doesn't work.
foreach($array as $element) {
foreach($element as $key => $value) {
if($key == 'id' && $value == 'searched_value'){
//delete this particular object from the $array
unset($element);//this doesn't work
unset($array,$element);//neither does this
}
}
}
Any suggestions. Thanks.
foreach($array as $elementKey => $element) {
foreach($element as $valueKey => $value) {
if($valueKey == 'id' && $value == 'searched_value'){
//delete this particular object from the $array
unset($array[$elementKey]);
}
}
}
Be careful with the main answer.
with
[['id'=>1,'cat'=>'vip']
,['id'=>2,'cat'=>'vip']
,['id'=>3,'cat'=>'normal']
and calling the function
foreach($array as $elementKey => $element) {
foreach($element as $valueKey => $value) {
if($valueKey == 'cat' && $value == 'vip'){
//delete this particular object from the $array
unset($array[$elementKey]);
}
}
}
it returns
[2=>['id'=>3,'cat'=>'normal']
instead of
[0=>['id'=>3,'cat'=>'normal']
It is because unset does not re-index the array.
It reindexes. (if we need it)
$result=[];
foreach($array as $elementKey => $element) {
foreach($element as $valueKey => $value) {
$found=false;
if($valueKey === 'cat' && $value === 'vip'){
$found=true;
$break;
}
if(!$found) {
$result[]=$element;
}
}
}
It looks like your syntax for unset is invalid, and the lack of reindexing might cause trouble in the future. See: the section on PHP arrays.
The correct syntax is shown above. Also keep in mind array-values for reindexing, so you don't ever index something you previously deleted.
This should do the trick.....
reset($array);
while (list($elementKey, $element) = each($array)) {
while (list($key, $value2) = each($element)) {
if($key == 'id' && $value == 'searched_value') {
unset($array[$elementKey]);
}
}
}
You can also use references on foreach values:
foreach($array as $elementKey => &$element) {
// $element is the same than &$array[$elementKey]
if (isset($element['id']) and $element['id'] == 'searched_value') {
unset($element);
}
}
I'm not much of a php programmer, but I can say that in C# you cannot modify an array while iterating through it. You may want to try using your foreach loop to identify the index of the element, or elements to remove, then delete the elements after the loop.