0

A question from PHP self-learner.

My question is how can one dynamically build an array.

I have an array of some class values

$tags;

a class tag has a field called Text;

I need to build an array of strings populated from that field

NOTE for downvoters. I am not PHP developer. I just need to do one simple task. I just do not know how to dynamically build an array of strings. That is my question. Hope this question will help other people who are learning PHP.

2
  • 1
    So the class is named tag and it has a public var named $Text and for an array of instances of this class you need to grab the value of $Text and create an array of strings? Commented Mar 8, 2011 at 19:56
  • CRasco, yes. Absolutely correct. Commented Mar 8, 2011 at 19:57

2 Answers 2

2
$textArray = array();

foreach($tags as $tag)
{
    $textArray[] = $tag->Text;
}

This will take each tag object in the $tags array and add the Text value to an array called $textArray.

If this isn't what you were looking for, please let me know and I will do my best to adapt my answer.

Sign up to request clarification or add additional context in comments.

Comments

1
class Tag {
    public $Text;
}

$tag1 = new Tag();
$tag2 = new Tag();
$tags = Array($tag1, $tag2);

Is that your problem? If so, keep in mind that PHP has loose data types so $Text could very well be a string. Try something like this:

$NewTags = Array();
foreach($Tags as $tag) {
    $NewTags[] = $tag->Text;
}

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.