Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Its a simple problem but i dont remember how to solve it

i have this array:

$this->name = array('Daniel','Leinad','Leonard');

So i make a foreach on it, to return an array

foreach ($this->name as $names){
                echo $names[0];                 
            }

It returns

DLL

It returns the first letter from my strings in array.I would like to return the first value that is 'Daniel'

share|improve this question

3 Answers 3

up vote 1 down vote accepted

try this one :

foreach ($this->name as $names){
        echo $names;  //Daniel in first iteration 
        //  echo $names[0]; will print 'D' in first iteration which is first character of 'Daniel'           
  }



echo  $this->name[0];// gives only 'Daniel' which is the first value of array
share|improve this answer

Additional answer concerning your results :

You're getting the first letters of all entries, actually, because using a string as an array, like you do, allows you to browse its characters. In your case, character 0.

Use your iterative element to get the complete string everytime, the alias you created after as. If you only want the first element, do use a browsing loop, just do $this->name[0]. Some references :

share|improve this answer

Inside your loop, each entry in $this->name is now $names. So if you use echo $names; inside the loop, you'll print each name in turn. To get the first item in the array, instead of the loop use $this->name[0].

Edit: Maybe it makes sense to use more descriptive names for your variables. For example $this->names_array and foreach ( $this->names_array as $current_name ) makes it clearer what you are doing.

share|improve this answer
    
I would like to return the first value that is 'Daniel' –  Amal Murali Nov 26 '13 at 18:50
    
@AmalMurali good point. Edited answer. –  P_Enrique Nov 26 '13 at 18:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.