Jump to content

Problem adding elements to array


Case-Sensitive

Recommended Posts

Hi Guys

 

Ive got an array called $links inside a class and i want to be able to add things to the end of this array (store info in the object). So what I did was to have a function, like so:

 

public function AddToLinks($ALinkObj)
{
$iter = (sizeof($this ->links)) -1;
$this ->links[$iter] = $ALinkObj;
//$iter++;
}

 

The problem is with this

$iter = (sizeof($this ->links)) -1;

, every time the array gets created (arrays start at 0) the function above will make the array position equal to -1.

 

Is there a clever way to avoid the array beginning from -1 and taking into account that a value is already present in position 0.

 

Any help would be great

Thanks alot

 

 

 

 

Link to comment
Share on other sites

I just looked the function up and it seems to do the same job as sizeof(), which ive used already.

 

$array[0] = "A"

$array[1] = "B"

$array[2] = "C"

$array[3] = "D"

 

The array above contains 4 elements, but because arrays start at 0 not 1 the position to place the next element needs to be -1 of the total elements.

 

Any other ways that this could be done

cheers for your thoughts.

Link to comment
Share on other sites

Oh! Sooooooooooooooooo sorry, I just got what you meant!

 

if Count() returns the number of total elements its there for returning the next position available

 

$array[0] = "A"

$array[1] = "B"

$array[2] = "C"

$array[3] = "D"

 

$array[count($array)] = "E" 

would place it in the next position which is 4!

 

Thanks fret, sorry for being a nooob!

Link to comment
Share on other sites

jesirose is right about the $array[] working to add to the end of the array; it works just the same as array_push but without the overhead.

 

You may also want to read up on array_unshift ( http://www.php.net/manual/en/function.array-unshift.php ) which adds one or more values to the beginning of an array and renumbers accordingly.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.