开发者

php function with arrays

I want to pass one argument to a function, rather than multiple arguments, that tend to grow unexpectedly. So I figure an array will get the job done. Here's what I've drafted so far...

<?php


function fun_stuff($var){
// I want to parse the array in the function, and use 


}


$my = array();
$my['recordID'] = 5;
$my['name'] = 'John Smith';
$my['email'] = 'john@开发者_高级运维someemail.com';

echo fun_stuff($my);

?>

I haven't quite grasped the concept of parsing an array. And this is a good way for me to learn. I generally pass the same variables, but on occasion a record does not have an email address, so I do need to make a condition for missing keys.

Am I doing this right so far? Can I pass an array as an argument to a function? And if so, how do I parse and search for existing keys?


Hopefully this isn't too far off topic...but you sounded like you were just trying to avoid multiple parameters when some can be NULL. So, I would recommend that you use an object instead of an array for clarity...that way, there is no confusion as to what properties should exist. If you're using PHP 5, you can also strongly type the parameter so nothing else can get in. So:

class Record {
    public $Id;
    public $Name;
    public $Email
}

function fun_stuff( Record $record ) {
    // you will now have better intellisense if you use an IDE
    // and other develoers will be able to see intended parameters
    // clearly, while an array would require them to know what's
    // intended to be there.
    if( !empty($record->Email) ) {
        // do whatever.
    }
}


Yes you are on the right track. The approach I take is put required paramters as the first parameters and all optional parameters in the last argument which is an array.

For example:

function fun_stuff($required1, $required2, $var = array()) {
   // parse optional arguments
   $recordId = (key_exists('recordID', $var) ? $var['recordId'] : 'default value');
   $name = (key_exists('name', $var) ? $var['name'] : 'default value');
   $email = (key_exists('email', $var) ? $var['email'] : 'default value');
}

Then you can call your function like so:

fun_stuff('val 1', 'val 2', array(
    'recordId' => 1,
    'name' => 'John',
    'email' => 'john@stackoverflow.com'
));


This is a bad design practice, but that's not the question here. You can "parse" array's like so...

if( array_key_exists( 'email', $var ))
{
   // use email field
}

If you need to, you can loop through all elements like so...

foreach( $var as $key => $value )
{
   echo '$var[\''.$key.'\'] = '.$value;
}


I'm not recommend you to use array for this.
You can define optional arguments with default values:

//$name and $email are optional here
function fun($record_id, $name='', $email='')
{
    if (empty($name)) print '$name is empty';
}

//Usage:
fun(5, 'Robert');
fun(5);
fun(5, 'Robert', 'robert@gmail');
fun(3,'','robert@gmail');

If you will use array, IDE will not be able to show autocomplete suggestions, it means more typos, and you have to remember all keys of this array forever or look at code of the function each time.


I'm not really sure what you want to achieve, but I suspect something like this:

$aPersons = array();
$aPersons[] = array('name' => 'name1', 'age' => 1);
$aPersons[] = array('name' => 'name2', 'age' => 2);

array_map('parsePerson', $aPersons);

function parsePerson($aPerson) {
    echo $aPerson['name'];
    echo $aPerson['age'];
}

The problem with your current array is that it only has one dimension. You can simple do echo $my['name'];. There are easier ways to parse arrays though.

foreach($aPersons as $aPerson) {
    echo $aPerson['name'];
    echo $aPerson['age'];
}

$iLength = sizeof($aPersons);
for($i = 0; $i <= $iLength; $i++) {
    echo $aPersons[$i]['name'];
    echo $aPersons[$i]['age'];
}


To parse and view, there is the signficant print_r function which gives out the array details.

When calling a function you need the return syntax at the end that will parse out anything you call in the return.


You obviously can pass array to the function. Inside it read the variable as you were assigning values before it. If you assign:

$my['key'] = 'value';

In you function use:

echo $var['key'];


Why you don't use a foreach to walk in array?

function fun_stuff($var){
    foreach($var as $key => $item){
        echo '[', $key, "] => ", $item, "\n";
    }
}
$my = array();
$my['recordID'] = 5;
$my['name'] = 'John Smith';
$my['email'] = 'john@someemail.com';
fun_stuff($my);


Yes, this is correct (though your question is a bit broad). You're already referencing the array values via indexes when you set up the $my variable. You can do the same thing within your function (with the $var variable).

I recommend taking a look at all of PHP's built-in array functions: http://php.net/manual/en/ref.array.php


Try this:

function fun_stuff($var){
// I want to parse the array in the function, and use 
    $fun_string = "";
    if( is_array( $var ) {
        if( array_key_exists( "name", $var ) )
            $fun_string .= "For " . $var["name"];
        else $fun_string .= "A nameless one ";
        if( array_key_exists( "email", $var ) )
            $fun_string .= " (email: " . $var["email"] . ")";
        else $fun_string .= " without a known e-mail address";
        if( array_key_exists( "recordID", $var ) )
            $fun_string .= " has record ID of " . $var["recordID"];
        else $fun_string .= " has no record ID set";
        $fun_string .= "\n";
   }
   return $fun_string;
}


Yes You can! Just pass the array and inside the function just use a foreach loop to parse it!

function myFunction($array)
{
  foreach($array as $value)
  {
    echo $value;
  }
}

or If you want to have full control over the pair key/value:

    function myFunction($array)
{
  foreach($array as $key=>$value)
  {
    echo "key:".$array[$key]."value:".$values;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜