Jump to content

Whats wrong with my function


EchoFool

Recommended Posts

Hey i have a function which grabs info and sends it back in an array with return().

 

But for some reason the script that recieves the data receives partial information here is an example:

 

 

 

 

 

 

 

<?php
function arrayget($pid,$aid){
$s = $db->getRow("SELECT field1,field2,field3,field4 FROM table1 t1

               INNER JOIN table2 t2 ON
               t1.id=t2.pid
               WHERE t2.pid='$pid' AND t2.aid='$aid'");   
print_r($s); //array displays correctly at this point
   foreach($s as $key=>$ss){  
   $var = 1;
    return array($ss['field1'],$ss['field2'],$ss['field3'],$ss['field4']);    
   }
}
$pid = 28;
$aid = 1;
print_r(arrayget($pid,$aid)); //displays incorrect values see below print out examples in bold
?>

 

The first print array shows:

Array ( [field1] => 5 [field2] => 2 [field3] => 5000 [field4] => 5000)

 

Second print shows:

Array ( [field1] => 0 [field2] => 0 [field3] => 0 [field4] => 0)

 

When i physically put $ss['field3'] = 5000; in the for loop the result became:

Array ( [field1] => 5 [field2] => 5 [field3] => 5 [field4] => 5)

 

I don't understand what i did wrong =/

Link to comment
https://forums.phpfreaks.com/topic/240849-whats-wrong-with-my-function/
Share on other sites

Well, I understand why you are getting the results you are getting, but I can't figure out what you are trying to do. The code makes no sense to me.

 

Here is what I see in the function:

 

1. You get the first row, as an array, from the query as $s

2. You do a foreach loop on $s using $key and $ss.

3. On the first iteration of the loop $key will be a string var as 'field1' and $ss will be a string var of '5'

4. You then try to return an array of values from the variable $ss. But you are referencing array indices for $ss and it is a string - so you are getting empty values.

 

If you want the array of values from the first row (assuming that is what you want since you say $s has the "correct" values. Then just return $s. There is no need to do a foreach loop.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.