Jump to content

Array in PHP


Deepzone

Recommended Posts

I use print_r to show display the content of two arrays. Apart from starting element (I guess), would there be any difference in terms of looping through the array. Please see the sample below:

 

Content of $col (from parm using $func_get_args)

Array ( [1] => a [2] => b [3] => c )

 

 

Content of $colarray (hardcoded)

Array ( [0] => a [1] => b [2] => c )

Link to comment
Share on other sites

It depends how you plan to spin over the array. you'll be able to use a foreach loop but anything that requires keys to be referenced like for loops you'll have to change the starting offset.

 

Here's some examples:

$array = array( 1 => 'first', 2 => 'second', 3 => 'third' );
foreach( $array as $element ){
echo $element . "<br />";
}
//prints first second third
//or we could reset the keys then iterate
$array = array_values( $array );
$count = count( $array );
for( $x = 0; $x < $count; $x++){
echo $array[$x] . "<br>";
}
//or if you want to be a right geek
$iterator = new ArrayIterator( $array );
while( $iterator->valid() ){
echo $iterator->current() . "<br />";
$iterator->next();
}

 

As for why element 0 wasn't used I'm not sure... Default behaviour in most languages when it comes to arrays is to start from 0.

Edited by exeTrix
Link to comment
Share on other sites

No difference besides the indexing. What's the code that gets it?

I use te following to grab the value from parm:

$func_num_args = func_num_args();

$func_get_args = func_get_args();

if ($func_num_args > 1) {

$column = $func_get_args;

 

}

Note: I always ignore the first parm.

Link to comment
Share on other sites

Just looking at the code above you don't need:

 

$func_get_args = func_get_args();

 

Why not do this:

$argsCount = func_num_args();
if( $argsCount > 1 ){
   $column = func_get_args();
}

 

 

Note: I always ignore the first parm.

 

By any chance are you unsetting $column[0] later in the script which would cause the element at offset 0 to be remove, hence the array keys starting from 1?

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.