Evet, it is possible to use a variable as indice, bir dizi elemanı erişirken.
Bir örnek olarak, bu kod bölümünü göz önünde bulundurun:
$results = array(
'a' => 'sentence a',
'b' => 'hello !',
);
$indice = 'a';
echo $results[$indice];
Aşağıdaki çıktıyı verecektir:
sentence a
Here, $indice is a quite simple variable, but you could have used whatever you wanted between the [ ve ], like, for instance :
- fonksiyonlar:
$results[ my_function($parameter) ]
- array element :
$result[ $my_array['indice'] ]
- Hangi yapmak istediğiniz ne gibi görünüyor?
- nesne özellik:
$result[ $obj->data ]
- ...
Temelde, sen orada ne istersen hemen hemen kullanabilirsiniz - sürece bir sayıl değer değerlendirir gibi (i.e. a single integer, string)
In your specific case, you could have $results declared a bit like this :
$results = array(
'q1' => 'first question',
'q2' => 'second question',
);
Ve $i bu şekilde ilan olurdu:
$i = array(
'question' => 'q1'
);
$i['question'] 'q1' olacak ve aşağıdaki kod bölümünün o demektir ki:
echo $results[ $i['question'] ];
Bu çıkışını alabilirsiniz:
first question
Edit : size soru başlığında kullanılan belirli sözcükleri cevaplamak için, ayrıca PHP variable variable strong> denen kullanabilirsiniz:
$variable = 'a';
$indice = 'variable';
echo $results[ $$indice ];
İşte:
$indice olan 'variable'
- ve
$$indice is 'a'
- hangi daha önce olduğu gibi aynı çıktıyı alırsınız demektir
And, of course, don't forget to read the Arrays section of the PHP manual.
Why is $foo[bar] wrong? em> paragraf firt yayınlanmıştır örneği göz önünde bulundurularak, özellikle ilgi olabilir.
Edit after the edit of the OP :
$value['questions'] ise 'q1', o zaman, kod aşağıdaki iki bölümleri:
if($results[$value['questions']]==4){blah blah blah}
ve
if($results['q1']==4){blah blah blah}
should do exactly the same thing : with $results[$value['questions']], the $value['questions'] part will be evaluated (to 'q1') before the rest of the expression, ve that one will be the same as $results['q1'].
As an example, the following portion of code :
$results = array(
'q1' => 4,
'q2' => 6,
);
$value = array('questions' => 'q1');
if($results[$value['questions']]==4) {
echo "4";
}
Çıkışlar 4.