使用foreach循环遍历变量名称

时间:2013-10-20 19:39:45

标签: php arrays

我有一个包含5个部分的for循环,每个部分都有相同的代码,只有不同的变量名称:

示例:

if($name=="bob"){
    // do things with $name1
}
elseif($name=="bob2"){
    // do things with $name2
}
// ...

如果有办法让我只做一个循环,我可以有一个变量名数组,即$ namearray =“$ name1”,“$ name2”..

然后循环可以在每次迭代时替换变量名吗?

3 个答案:

答案 0 :(得分:3)

$names = array('bob', 'bob2');
// array of processed names

foreach($names as $name){
   // do things with current name, which is in variable $name
   // each itteration it will be next name from your array: bob, bob2
   echo "Current name - $name <br />";
}

答案 1 :(得分:2)

$namearray = array('bob','bill');

foreach ($namearray as $n){
//do something with $n (bob, bill) et al
}

答案 2 :(得分:0)

<?php

    $name1 = 'Bob';
    $name2 = 'Sarah';
    $name3 = 'Foo';


    // http://php.net/manual/en/language.types.array.php
    // http://php.net/manual/en/function.array.php
    // http://php.net/manual/en/ref.array.php
    $arrayOfVariableNames = [$name1, $name2, $name3];
    // the above can also alternatively (if the $name variables are not used elsewhere) be written in less code to avoid having less variables 
    /// $arrayOfVariableNames[0] = 'Bob'; $arrayOfVariableNames[1] = 'Sarah'; 
    // or even like
    /// $arrayOfVariableNames = ['Bob', 'Sarah', 'Foo'];


    // http://php.net/manual/en/control-structures.foreach.php
    // http://php.net/manual/en/control-structures.for.php 
    foreach ($arrayOfVariableNames as $key => $name)
    {
        // http://php.net/manual/en/control-structures.switch.php
        // http://stackoverflow.com/questions/15903193/php-switch-vs-if
        // http://phpswitch.com/
        // the content from here could be passed into a(nother) function to keep each part of the code doing its job, and doing it well
        // these can be written with ifs, but if there are many different options a switch is most likely your best bet
        switch ($name)
        {
            case 'Bob':  
                // do things with $name...
                break;

            case 'Sarah':  
                // do things with $name... for example, previously in the code create an array $namesBeginningWith and assign each letter of the alphabet to the array as a key, and the initial value at each position to 0, then increment the count  $namesBeginningWith['S']++; could be done with any language, just for fun
                break;

            case 'Foo':  
                // do things with $name... for example, echo 'Foo is the name, Foo Bar';
                break;

            case 'Bar':  
                // do things with $name... for example, 
                /// you wanted to replace the variable names, so here you could do $arrayOfVariableNames[$key] = 'Bob2'; 
                //// No Bar's allowed! 
                break;

            default:
                // if the name is not one that you know, do something "else" with it!
            break;
        }
    }


    /* 
        // for some extra fun, you asked to "do things with $name2"

        // http://stackoverflow.com/questions/2206387/what-is-a-class-in-php/2206835#2206835
        // http://php.net/manual/en/language.oop5.php
        class Person
        {
            private $name;
            private $age;

            // http://php.net/manual/en/language.oop5.typehinting.php
            // http://www.sitepoint.com/type-hinting-in-php/
            public function doStuffWith(Person $person)
            {
                return ($this->name . ' and ' . $person->getName() . " just did stuff! \n\n");  
            }

            public function setName($name)
            {
                $this->name = $name;
            }
            public function setAge($age)
            {
                $this->age = $age;
            }
            public function getName()
            {
                return $this->name;
            }
            public function getAge()
            {
                return $this->age;
            }
        }

        $person1 = new Person();
        $person1->setName('Bob');
        $person1->setAge(21);

        $person2 = new Person();
        $person2->setName('Sarah');
        $person2->setAge(21);

        $person3 = new Person();
        $person3->setName('Foo');
        $person3->setAge(42);

        $peopleList = 
        [
            $person1->getName() => $person1, 
            $person2->getName() => $person2, 
            $person3->getName() => $person3
        ];

        foreach ($peopleList as $key => $person)
        {
            // if ('Foo' !== $person->getName())
            echo $person->doStuffWith($peopleList['Foo']);
        }
    */

?>