0

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'

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I would like to return the first value that is 'Daniel'
0

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 :

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.