Problem with Single Array

General discussions related to php

Moderators: macek, egami, gesf

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

Problem with Single Array

Post by 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)
{

}

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

Re: Problem with Single Array

Post by 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

Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest