finding data in an array

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi Folk

I have the following function:

function getdata($sql) {
 $result = @mysql_query($sql) or die("Error: " . mysql_error()." sql was  
 $ret = array();
 while($row = mysql_fetch_assoc($result)) {
  $ret[] = $row;
 return $ret;

I love it, because all I need to do is to stick in some sql (e.g. Select *  
from clients) and away she goes like this

$data = getdata($sql)
foreach($data as $ds) {
 echo '<p>'. $ds["first_name"].' '.$ds["first_name"].'</p>';

Now, what I want to do is check the fields for all $ds arrays.  That is, I  
want to check one particular field for all the "rows" and check that it is  

What is the most efficient way to do this? Is there a function that I can  
use?  Something like

function datafieldcheck($ma, $fld) {
//$ma = a multidimensional array from the getdata function
//$fld = the field to check
 foreach($multiarray as $ds) {
  $v = $ds[$fld];
  if(!$first) {
   if ($v != $vex) {
    return false;
  $vex = $v;
  $first = 1;
 return true;

Re: finding data in an array

windandwaves wrote:
Quoted text here. Click to load it

AFAIK, there isn't an out-of-the-box function for this, so all I can offer  
you is an alternative to what you have posted:

function datafieldcheck($ma, $fld) {
   $current = current($ma);
   if (isset($current[$fld])) {
      $v = $current[$fld];
      while (false !== ($current = next($ma))) {
         if (!isset($current[$fld]) || strcmp($v, $current[$fld])) {
            return false;
      return true;
   return false;


Re: finding data in an array

On Sat, 14 Jan 2006 22:24:24 +1300, windandwaves wrote:

Quoted text here. Click to load it

To do it with the SQL. If you want to check one particular field  
in your table, you would write your SQL as  

$sql="select * from some_table where

The main rule of writing a database application is: whatever you can
do in the database, do in the database. That's what you have the database
for: to provide some intelligence for the data retrieval. Why bother using
database when you're using it as a flat file?


Re: finding data in an array

Can't think of a way to do this that's signicantly better. The
following examines all the cells and return the columns where all rows
contain identical values:

$same = call_user_func_array('array_intersect_assoc', $rows);

Site Timeline