Board index   FAQ   Search  
Register  Login
Board index PHP PHP General

Problem with Single Array

General discussions related to php

Moderators: macek, egami, gesf

Problem with Single Array

Postby kheadley » Wed Feb 27, 2013 1:07 pm

Hello All,

I have a function that returns an values in an array, the problem is that sometimes that array only has a single value in it. If I use a for each loop it fails as there are not more than one row in the array.

I can't use $array[0] as I need the key value as well and this is not always 0. Any ideas on how to get the value out of the array with the key as well.

Code: Select all
foreach($pos as $key => $value)
{

}
kheadley
New php-forum User
New php-forum User
 
Posts: 14
Joined: Sat Jan 07, 2012 3:03 pm

Re: Problem with Single Array

Postby seandisanti » Wed Feb 27, 2013 1:51 pm

Code: Select all
<?php
    
function arrayContents($data=array()){
        if (empty(
$data)){
            return 
'array is empty';
        }
        
$output '';
        foreach (
$data as $key=>$value){
            
$output.=$key ' = ' $value ' <br />';
        }
        return 
$output;
    }
    echo 
'empty array: ' arrayContents(array()).'<br />';
    echo 
'single element array: ' arrayContents(array('foo'=>'bar')).'<br />';
    echo 
'multiple element array: <br />' arrayContents(array('this'=>'is a long way','to_replace'=>'print_r'));


***edit**** output of running the above script is:
empty array: array is empty
single element array: foo = bar

multiple element array:
this = is a long way
to_replace = print_r
seandisanti
php-forum Fan User
php-forum Fan User
 
Posts: 787
Joined: Mon Oct 01, 2012 12:32 pm


Return to PHP General

Who is online

Users browsing this forum: No registered users and 2 guests

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.

cron