Reputation: 2233
So I have PHP array called 'tags', which is being filled with objects that I get from the model. And I need to push one more element into this array, which should be an empty string. For now my code looks as follows:
$tags = [];
$tags = compact(WebsiteTag::all());
array_push($tags, '');
return $tags;
And as a result I get an array where the only element is this empty string. The same happens if I try to push some actual string -- just this string remains in the array. I've tried also creating an array like:
$tags = [];
array_push($tags, compact(WebsiteTag::all()), '');
return $tags;
And
array_push($tags, WebsiteTag::all(), '');
And also
$tags = array(WebsiteTag::all(), '');
But in these cases I get an array of two elements, where the first one is an array with objects and the second one is my empty string. Is it possible to create an array of different type elements? And if it is, how should I push them correctly?
Upvotes: 2
Views: 4412
Reputation: 1190
If WebsiteTag::all() returns an array you could simply merge them together:
$tags = array_merge(WebsiteTag::all(), ['']);
See the documentation of array_merge() for details
Upvotes: 3
Reputation: 9123
I cannot know for sure what WebsiteTag::all()
returns but I think the result is an array of tags. So what I would do is one of these two options:
$tags = WebsiteTags::all();
$tags[] = '';
// Or
$tags = array_merge(WebsiteTags::all(), array(''));
Upvotes: 3
Reputation: 2233
Well I got it by doing as follows:
$website_tags = [];
$tags = WebsiteTag::all();
foreach ($tags as $tag) {
array_push($website_tags, $tag);
}
array_push($website_tags, '');
Upvotes: 0