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
https://forums.phpfreaks.com/topic/274790-array-in-php/
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.

Link to comment
https://forums.phpfreaks.com/topic/274790-array-in-php/#findComment-1413983
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
https://forums.phpfreaks.com/topic/274790-array-in-php/#findComment-1414003
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
https://forums.phpfreaks.com/topic/274790-array-in-php/#findComment-1414004
Share on other sites

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.