Problem with Single Array

General discussions related to php

Moderators: egami, macek, gesf

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

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)


php-forum Fan User
php-forum Fan User
Posts: 974
Joined: Mon Oct 01, 2012 12:32 pm

Wed Feb 27, 2013 1:51 pm

Code: Select all

    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

Post Reply