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
https://forums.phpfreaks.com/topic/36723-problem-adding-elements-to-array/
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.

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!

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.

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.