Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Arrays : Returning A Reference To An Array Item ??


I am currently storing a set of objects inside an array,

$itemlist = array();
$itemlist[] = new item("myitem");
//...

and I am looking to develop a search function, which returns a
reference to the found item.

function &search_item($itemlist,"myitem") {
//...
}

I am trying to figure out how to obtain a reference to a given item in
an array.
Indeed, foreach() and each() seem to work on copies of the data in the
array.
For example:

$array = array("a","b","c","d");
print_r($array);
foreach($array as $v) $v="xxx";
print_r($array); // $array is unchanged

reset($array) ; while(list(,$v)=each($array)) $v="xxx";
print_r($array); // $array is unchanged, again




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Php Extension: Returning Array Of Arrays
it's my 1st week of PHP so forgive me for such a basic question. I'm
trying to return an array of arrays of strings from a home-made PHP
extension module. My current code looks like :

ZEND_FUNCTION(..)
{
...
array_init(return_value);
add_next_index_long(return_value, nb_of_arrays);
for ( ... ) {
zval *one_array;
array_init(one_array);
add_next_index_long(one_array, nb_of_strings);
for (...) {
add_next_index_string(one_array, string[..],1);
}
add_next_index_zval(return_value, one_array);
}
}

This causes a failure in Apache.

Before debugging my PHP extension tomorrow morning (e.g. to suppress the
useless '# of items' in each array ;-), can anybody tell me whether this
is the proper way to achieve this ?

Returning Autogenerated ID On New Item
Lets say you have a form that when saved to the mysql database creates
a unique incremental id. The form is just the first part of a series
of things the user can do, so once the ID is created, the page would
need to know immediately what this ID is. Is there a way to grab this
ID instantly once it is created? Obviously if this were a sign-up for
and a new user name and password are involved, you can have the user
login after the initial set up and this select statement would bring
back the ID. But the situation I have doesn't work like that.

The way I have been dealing with this is simply to have a select
statement after the initial insert that requests the record based on a
couple of other fields that are likely unique. But this seems like a
rather kludgy way of doing it. Is there some other solution.

Array_unique - How-to Get First Item Value In Repeated Array Item
I would like to know how-to get the first value of repeated items too in an array using something like array_unique. Code:

Returning A Null Reference In PHP 4.4.2
Consider a class that encapsulates an associative array. It has two
"setter" methods:

class A
{
....
function setAttribute( $name, $value )
{
$this->attributes[ $name ] = $value;
}
....
function setAttributeByRef( $name, &$value )
{
$this->attributes[ $name ] =& $value;
}
....

The following "getter" method *used* to work just fine prior to version
4.4.2:

....
function & getAttribute( $name )
{
if ( isset( $this->attributes[ $name ] ) )
return $this->attributes[ $name ];
return NULL;
}
....

However, as of version 4.4.2, this throws a "FATAL: Only variable
references should be returned by reference." error. Unfortunately, my
host (and several of my client hosts) are stuck on this version.

Is there an elegant way to solve this problem? I want to return a value
indicating that no such attribute exists.

(I've googled the problem and can't find anything useful other than a
suggestion in a PHP bug report that I learn how to write "proper"
code.)

Returning A Reference To A Class Variable
I have a class which contains (1) a class variable and (2) a method
(e.g., methodA) which returns a reference to the class variable. If
the variable has been assigned a value by a constant initializer in
the "var" statement, my httpd process crashes with a segmentation
fault when I call methodA. If the variable is assigned a value in one
of the class methods, the httpd process does not crash when methodA is
called and the value returned is the expected value. This is true
even if the variable was first initialized in the "var" statement, as
long as its value is subsequently set in a class method.

Fails:
class C {
var $v = "hello";

function C () {
}

function &methodA () {
return ($this->v);
}
}

Succeeds:
class C {
var $v = "hello";

function C () {
$this->v = "hello";
}

function &methodA () {
return ($this->v);
}
}

Passing By Reference Better Than Returning A Value When Calling A Function?
When I need a function to generate a string, I have two methods:
1. pass by reference: mystring = ""; myfunction( mystring ); // prototype of myfunction( &anystring );

OR

2. mystring = myfunction(); //which return a string. According to experience of C/C++, the former one is better as of the...

Test If An Item Is An Object Or A Reference To An Object
Using php 4.4.4, let's say I have an array of objects or references to
objects. If I picked out an arbitrary element, $n, how would I know
if that was an object or a reference to an object?

Deleting An Array Item
I have a standard array:
$foo = array(
0 => 'abc'
1 => 'def'
2 => 'ghi');

and I have a variable, $bar, which equals 'def' ... and I want to check
my array to see if the value of $bar exists in the array, and if it
does, delete it from the array.

if (in_array($bar, $foo)) {
// what goes here???
}

I've done this before, but for the life of me, I'm drawing a blank now.
Help a bruthah out?

Random Item Of An Array
What is the best way of picking out a random item of an array, regarding speed and CPU-usage ? I need a super fast way of picking out an ID from my MySQL db.

Delete Item From Array
How do I search for an item within an array, then delete it?

Remove An Item From And Array Entirely
How do you remove an item from an array...

Delete An Item From An Index Array?
How can I delete an Item from an index array in php4?

Shopping Cart Item Array
Trying to build a small simple shopping cart and I am having difficulty getting the solution. The cart is displaying each product, but it is overwriting the values. So if I have added 10 products, it shows ten items, but each item has the values of the last product I added.

I think that this may be due to me trying to use a key to store both an array and string at once, but Iam not sure. I have looked at other examples but due to different methods, syntax is throwing me off. Code:

Remove A Single Item From An Array
I have gathered an array of ID's. I need to go throught the array and find a specific ID and remove it from the array. Because we want to keep that ID. Any suggestion of how to do that.

Preg_split First Item In Array Is Blank
could someone please explain to my why using the code below generates a blank item in $array[0] please. The 'x' from xbox360 is in $array[1]?

Deleting A Single Item From The Middle Of An Array?
I have an array that contain objects, I want to be able to test against the id of that object and remove it from the array. In it's simplest for I want to go from this:

$people = array('Tom', 'Dick', 'Harriet', 'Brenda', 'Jo');

...to this...

$people = array('Tom', 'Dick', 'Brenda', 'Jo');

The fact that the items in the array are objects should not matter right? Plus I've already written my loops and conditionals to check which item i need to remove.

function removeItem ( $item ) {
   $len = count ( $_SESSION['basket_arr'] ) ;
   if ( $len == 1 ) {
      emptyBasket ( ) ;
   } else {
      for ( $i = 0 ; $i < $len ; $i++ ) {
         if ( $item->id == $_SESSION['basket_arr'][$i]->id ) {
            //$_SESSION['basket_arr'][$i] must go
         } } }}


Removing Item From Array Then Overwriting File
I have a bookings.txt file which has a list of dates each on a new line, for example: -

21/06/07
22/06/07
29/06/07
25/12/07
01/01/08

I also have a variable $event_dd_mm_yy which I want to remove from this file if found. Code:

How To Reference An Array In Multidimensional Array?
How do I reference an array within an array?

$mapped_array = array_map(null, $data_array, $counter_array);

// okay, so now I have an array of 2 arrays - but how do I reference each
array?
// the next two lines fail to give an accurate count
echo "Starting with ".count($mapped_array[0])." elements in
data_array<br>";
echo "Starting with ".count($mapped_array[1])." elements in
counter_array<br><br>";

// now I want to start at the bottom and look for an IP in each line of
data_array
// which I assume is mapped_array[0]
for ( $i=count($mapped_array[0]); $i > 0; $i-- )
{
$data_line = $mapped_array[0][$i];
$data = explode("|", $data_line);
if( in_array($ip, $data) )
{
// if there's a match, element[$i] of both arrays needs to be spliced
out
array_splice($mapped_array,$i,1);
}
}
// again, these next two lines fail to return an accurate count
echo "Ending with ".count($mapped_array[0])." elements in data_array<br>";
echo "Ending with ".count($mapped_array[1])." elements in
counter_array<br><br>";

Is there something about array_map that prevents me from referencing the
arrays within the array?

Passing An Array As A Reference To A Function
Noobie here (C++/C/Java experience though) ...

Recently picked up PHP ...

I want to pass an array to a function and then to use count on the
passed variable - is this the way to do it (its an object method) :

public function foo(array& $arr)
{
if (count($arr) < 1)
throw new MyException("Blah blah ...") ;
....
}

I have two questions for the pros:

1). Is the function signature correct (valid syntax?)
2). Can count accept a reference type variable ?

Array Creation As Reference, Or Always Copied?
Throughout the PHP manual, and normal code, one finds this construct:
$var = array( ... );

However, as far as I can tell this is quite inefficient, since it
always means two arrays are being created. The right-side array is
created, and then copied to the left-side variable.

Thus one would expect the normal syntax should be:
$var =& array( ... );

But this is not used in the manual very often.

So, is there some kind of magic on the first array assignment such that
it is done by reference (the first time)? Or are the vast majority of
examples of array creation in the manual (and most PHP code)
inefficient?

Push To Array Passed To Function By Reference?
Anyone know how to push values to an array that was passed to a function by reference.
This doesn't work:

function something(&$somearray) {
array_push($somearray,"new value"); }

Query Returning Array
I'm missing something very obvious, but it is getting late and I've
stared at it too long.

I am writing a basic function (listed at the bottom of this post) that
returns data from a query into an array.

The intent is that the following code:
$foo = dbSelectData("SELECT foo, bar FROM table", $link);
would return an array with the keys: 'foo' and 'bar'.

But what I get is instead a multidimensional array.
Doing a var_dump on $foo turns out to be
array(2) {
["foo"]=>
string(5) "Stuff"
["bar"]=>
string(10) "More Stuff"
}

I'm wondering where I went wrong in writing the function below.

function dbSelectData($query, $connection, $rtype=MYSQL_ASSOC){

$result = mysql_query($query, $connection);
if(!$result){
dbThrowError("Error in function dbSelectData. Query Was <em>
$query</em>.");
return FALSE;
}
else{
$numrows = mysql_num_rows($result);

if($numrows == 0){
return FALSE;
}
else{
while($rows = mysql_fetch_array($result, $rtype)){
$output[] = $rows;
}
mysql_free_result($result);
return $output;
}
}
}

Returning Array Value From Function
I have a function whose purpose is to return an array of values to be used elsewhere on a page, but I can't seem to get it to ouput the array. (When I try to reference the $territory variable outside the function I get nothing.) Here's my function: Code:

Returning A 2 Dimensional Array
I am trying to program a function to return a 2 dimensional array, but
it's not working. I reduced the return value to 1 dimension and
tested that to make sure that the problem wasn't elsewhere. It had no
problem when the array was 1 dimensional.

Is there something different I need to do in order to return a 2
dimensional array from a function?

Returning An Array From A Function
I have a function (fileTree) that recursively reads all the files in a
directory passed to it, and returns an array of the files, I have included
the code for this function below.

When I call this function, the bit of debug code at the end will correctly
print the array of files I am expecting, and then returns.

However, what is returned form the function isnt the array, is a scalar that
just contains the value of the last element in the
array

I am calling the function like this:

Returning An Array Data
I am parsing an XML file and returning the data back as an array. However, nothing returns back even though I can echo the data to the screen. Here is the code:

Sorting Though Array Returning Hightes Number
OK. I need to get data from a table row and then sort though it finding the highest value (number). This is how far I got.

Returning An Array Indexed By Numbers With MySql
Anyone know how to get an array indexed by numbers (i.e. - NON - Associative)? Seems like it should be able to be done with a function - but I haven't been able to find one.

Returning An Array To Populate A Drop Down Menu
Scenario: two related tables (Many) 'patient' and (one) 'doctor'. In the patient table, each row has an entry for doctor_id.

I have created a drop down menu on my patient form to input the doctor_id. The dropdown only shows the doctors' names.

This menu is generated by a SELECT statement on the doctor table. The result of SELECT goes into an array, and then each element of the array is inserted into the dropdown with a 'while' loop. This works fine.

However, I wish this dropdown to set itself to the correct doctor's name, when I retrieve a previously inputted patient record. That is, if patient 'Smith' is allocated to doctor 'Neo', the record is then saved, and later I retrieve the record: I wish to see doctor's name (Neo) as the default in the dropdown menu.

Returning Text Input Type As Array
I'd like to make all the text inputs in this form to be part of an array. The reasoning is that the form is built dynamically so there are times when there are 4 inputs while other times it's 12. When the form is submitted I need those inputs to be error checked and such.

Mailparse_msg_get_structure Returning Single Valued Array
I am writing code to strip out and write key data to a database from incoming e-mail.  I am using the mailparse functions to handle the incoming mail.  My code pulls in the e-mail fine, but the array returned by the mailparse_msg_get_structure() only has one row.  The entire contents of the /var/mail/$user file is being put into one row instead of it being broken apart into individual messages.  Here is the code:

Returning A Script Of Code As A String In An Array?
The below code is part of a pagination script in a function. I want to return this section in an array value but I am not sure how its done. I included what I have been trying.. Code:

Reference Stays Reference Even If Passed By Value
I started porting a huge PHP application to PHP5 and encountered a
problem with references. I don't know whether the behavior I see is a
bug or a feature. The following nonsens test program should make clear
what's the problem:

class test {
public $_foo = null;

public function __construct($foo) {
$this->_foo = $foo;
}
}

function fct1(&$p) {
print "before call to fct2(): $p->_foo
";
fct2($p);
print "after call to fct2(): $p->_foo
";
}

function fct2($p) {
print "in fct2(): $p->_foo
";
$p->_foo = "bla bla bla";
print "after modifying value parameter fct2(): $p->_foo
";
}

$t = new test("Hello World!");
fct1($t);

If I evaluate this code with php v5.1.2 I get the following output:

before call to fct2(): Hello World!
in fct2(): Hello World!
after modifying value parameter fct2(): bla bla bla
after call to fct2(): bla bla bla

I don't understand this: fct1() takes a parameter as reference, so
fct1() should be able to change the argument I pass to it, but it does
not do this. Instead it call fct2(), a function that takes a "value
parameter". In my understanding, fct2() can change its argument, but
changes to not affect the caller, ie. changing the parameter should
not affect the variable passed to it in the callers scope.

Am I wrong or is this a (known) bug?

BTW: The PHP4 version works fine with php4.

Getting Values In An Array Of Arrays
The following is the output of a print_r on an array. The value of
element[0] is itself an array. How do I access the elements in the
second array?

Array ( [0] =Array ( [Vancouver] =Vancouver [Eugene] =Eugene
[Beaverton] =Beaverton ) )

I've tried to set $c[] = $city[0], but this just outputs the same
result.

Array Sort: Multidimensional Arrays?
I'm horrible at arrays. And I'm now using a script that has a lot of neat predefined functions and things that I adore and would never have time to come up with myself.

I'm facing a problem with sorting an array in it though. Can't figure out where to really go in and... determine how to get the info displayed in correct order.

the $tpl->assign_block_vars basically creates a loop out of variables to output using a html template. Now... I want all this sorted by the variable called 'CURRENT'. Can't do ORDER BY in the sql statements since it's nested within a other sql statement call etc. Any help would be apprecciated. Here's the code: .....

Inserting Arrays Into A Holder Array From A Form
Need to put arrays of info into a holder array. for the moment i am creating the arrays from form info like so...

<input type="text" size="30" name="link1[title]">
<input type="text" name="link1[link]" size="30">
<input type="text" name="link1[description]" size="30">

and i thought if i did..

<input type="text" size="30" name="alllinks[link1[title]]">
<input type="text" name="alllinks[link1[link]]" size="30">
<input type="text" name="alllinks[link1[description]]" size="30">

it might work, but no, how do i add the array 'link1' into the holder array 'alllinks'.

Multiple Array Selection From Database Instead Of In-Page Arrays
Have posted before, but will simplify problem here. For original post go to
http://forums.devshed.com/t80025/s.html

I have setup 2 arrays like so in my one page script:

Code: ( php )

Iterator First Item?
Let's say I have the code:

foreach($data as $row)
{
do something with each $row
}

Is there a way to do something specific to the first item iterated?
Pseudocode:

foreach($data as $row)
{
if first time through iteration do something with $row
else do something which each remaining $row
}

Is this possible? I think I could use a regular 'for' loop, using the
length of the $data array as a guide, and then an 'if..else' structure
to see if it is the first time through the 'for' loop, but I was
looking for a more elegant solution.

Get One Row, One Item From Database
I was trying to grab just one row and one field in that row from MySQL, but couldn't find a way other than: PHP Code:

Trying To Split The Item...
I'm trying to make a search thru my mySQL database, so it any keywords are found then I'm adding the details to the next item in an array that I create. I've tested the array and it is storing the information into the array properly because it echoes out all of the information correctly. My problem is that, at the beginning of each item in the array I have information that tells me what part of the database it was pulled from and the id number and also how many times the a keyword was found in that specific database entry. So you have something like this.. Code:

Get Last Item In URL String
I realize how elementary this is, I apologize. Maybe that's why I can't find the right answer. I've tried everything from EXPLODEing the string to SUBSTR_REPLACE.

Can anyone tell me how to just get the last item in a URL string? Like turn this:

/mydirectory/myimg.jpg

into this:

myimg.jpg

Search Item In Database
I made a function that does a case insensitive search. This works fine.
But i'd like to improve that script so that it also returns items from the database that are partly similar to the search string.

this is the script atm:

Delete Item From Database
I still can't figure out how to delete an item from my shoppingcart. I have tried different ways to do this, but its impossible.

-a button or link that deletes a item from my database
-the php script that deletes it

here is a suggestion:

$slett = "DELETE ID, VARE, MODELL, STR, ANTALL, PRIS,
TOTALPRIS FROM USER_TRACK
WHERE USER_ID = "$user_id"";

But how can i assign this to a button?

Updating Item Numbers (or IDs)
After a while of deleting records in a MySQL db, there gets to be the
gaps in the id numbering system. i.e. 1, 2, 3, 6, 7, 12, and so on.
Is there a way to renumber the id system in a table for 1, 2, 3, 4, 5,
6, etc without manually going in and changing those numbers?

What Does `Catalog`.item Like '%A-%' Mean? -MySQL?
I am looking at an old query and I cannot remember or figure out what this
part of the query means:

`Catalog`.item like '%A-%'
It is the like '%A-%'

I cannot figure out.

Then entire query is:[color=blue]
> SELECT *
> FROM `Catalog`
> WHERE `Catalog`.img_status = &#391;' AND `Catalog`.item_type ='R' AND
> `Catalog`.item like '%A-%'
> ORDER BY `Catalog`.item_type[/color]

And will not work without the Like part

Pulling In One Item Of Four Categories
Ive got an offers table which contains name, category_id

I want to display all offers, however the first page will only display four offers (one of each category). My query is as follows so how do I do this part? Code:

Finding # Of Item From Query
I have a query that goes "SELECT item_name FROM products WHERE products.drink = 'juice'" . If I get back 12 results from this query I can make a list using a simple loop, that is fine . If I click on one of these list items I want to go to a detail page, again I can do this no probs.

How do I carry over to the detail page the number that the item appeared in the original list, for example if a result was "orange" and it was the 5th one in the list, how do I carry over the number 5 to the detail page?

Populating Form Item From SQL Enum Set Rev#2
$sql = "SHOW COLUMNS FROM table LIKE 'subject' ";
$qry = mysql_query($sql) or die("Query not valid: " . mysql_error());
$res = mysql_fetch_object($qry);
// This returns a row with a field 'Type' containing 'enum(...)'

$res->Type = str_replace('enum('', '', $res->Type);
$res->Type = str_replace('')', '', $res->Type);
//now the string is something like this: one','two','three

$temp = explode('','',$res->Type);
//temp is an array with as much elements as the enum

while ($temp)
print array_pop($temp);


This way is much more easier using the elements since they are elements
of an array. Cleaver isn't it?

How To Replace An Item In The Url Search String
Using PHP 4, what is the most elegant way to replace a parameter
value in a url query string? I want to replace the "Order" parameter,
but it could occur anywhere in the query string.

myfile.php?Param1=Hi+there&Order=ColumnA&Param3=Bye+Bye
myfile.php?Order=ColumnA
myfile.php?Param1=Anotehr+example&Order=ColumnA

after applying this function, I'd like the result of the above examples
to be

myfile.php?Param1=Hi+there&Order=ColumnB&Param3=Bye+Bye
myfile.php?Order=ColumnB
myfile.php?Param1=Anotehr+example&Order=ColumnB


Copyright © 2005-08 www.BigResource.com, All rights reserved