PHP Array during echo - php

I have an assignment to do but am having trouble understanding the given psuedocode :/
<?php
$bucket = new array();
print $bucket->addrocks('Rock1')->addrocks('rock2')-
>addrocks('Rock3');
echo "<h1>My Bucket</h1>";
echo "<ul>";
foreach($bucket as $rock){
echo "<li>". $rock ."</li>";
}
echo "</ul>";
?>
Now my trouble starts with understanding how they want me to construct the array after the "print" call? i am not looking for a direct answer to this just maybe a tutorial link or a finger in the right direction
Thank you in advance

In PHP, new is only used for instantiating objects Furthermore, array is a reserved word in PHP, so name your class something else. To instantiate an array in PHP you do this:
$my_array = array();
Now to add items to the array you would do this:
$my_array[] = "Rock 1";
$my_array[] = "Rock 2";
$my_array[] = "Rock 3";
To traverse the array you can use any type of loop, but usually you would just use a foreach loop.
For example:
foreach($my_array as $key => $value) {
echo $value . "<br />";
}

The problem lies in the array construction. This is how one constructs an array in PHP:
one by one:
$bucket = array();
$bucket[] = "Rock1";
$bucket[] = "Rock2";
$bucket[] = "Rock3";
All at once:
$bucket = array("Rock1","Rock2","Rock3");
The documentation: http://php.net/manual/en/language.types.array.php

Well unlikely but may be the array is not an construct but an class in your pseudocode. My assumptions depend on the use of new keyword and the user of -> and addrocks which looks like a method.
So, create a class called array (stupid I know) and get going.
However the user of foreach($bucket) also shows that it expects $bucket to be array. So decide wisely :)
May be use a magic method called __toString() inside the class and return back the array.

Related

PHP array unique on multi dimensional array/object

I've been trying for a while. I have tried several things to fix this, but I just can't get it to work.
My code:
<?php
if (is_array($row))
{
foreach ($row as $data) {
echo array_unique($data->username);
}
}
?>
It gives me the following error
Message: array_unique() expects parameter 1 to be array, string given
I have no idea what is going on with this. I have even tried placing the array_unique in the $row.
So like:
<?php
if (is_array($row))
{
foreach (array_unique($row) as $data) {
echo $data->username;
}
}
?>
But this gives me another error:
Object of class stdClass could not be converted to string
I have no idea what's going on. I have searched for hours but haven't found anything on here. Any help is greatly appreciated. Thanks.
You can't use array_unique on multi-dimensional arrays when you're looking inside the depth. Its works on flat one, and certainly won't work on strings. An alternative is to create another container for that and use usernames as keys, then you'll get unique ones.
Since you haven't shown the array/object structure, here a little bit on an idea on the comment I gave above:
$container = array();
foreach($row as $data) {
if(!isset($container[$data->username])) {
$container[$data->username] = $data;
}
}
// $container = array_values($container); // optional simple reindex

Converting XML file elements into a PHP array

I'm trying to convert a Steam group members list XML file into an array by using Php.
The XML file is: http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml
The elements are the member's steam IDs, such as 76561198000264284
How can I go about doing this?
Edit: So far I've used something like this:
$array = json_decode(json_encode((array)simplexml_load_string($xml)),1);
It outputs the first few elements, not ones specifically
from
This should return the fully accessible array:
$get = file_get_contents('http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml');
$arr = simplexml_load_string($get);
print_r($arr);
You can now access items like this:
echo $arr->groupID64;
echo $arr->members->steamID64;
Edit:
To parse the streamID, you can do a for loop
$ids = $arr->members->steamID64;
foreach($ids as $id) {
echo $id;
}
you can use below functional code to get your correct answer
<?php
$getfile = file_get_contents('http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml');
$arr = simplexml_load_string($getfile);
foreach($arr->members->steamID64 as $a => $b) {
echo "<br>".$a,'="',$b,"\"\n";
}
?>
OUTPUT
steamID64="76561198009904532"
steamID64="76561198004808757"
steamID64="76561198000264284"
steamID64="76561198016710420"
steamID64="76561198005429187"
steamID64="76561198030184436"
steamID64="76561197980763372"
steamID64="76561197972363016"
steamID64="76561198045469666"
steamID64="76561198010892015"
steamID64="76561198028438913"
steamID64="76561197967117636"
steamID64="76561197980283206"
steamID64="76561197992198727"
steamID64="76561198018960482"
steamID64="76561198071675315"
steamID64="76561198010447988"
steamID64="76561198025628761"
if you wish to customize you can make it as per your need. let me know if i can help you more..

how to create a collection of array type variable with somepart of variable names similar and other part is incrementing?

I want to make 10 variables with name as answer-1,answer-2,answer-3 and so on. Can i use for loop in such a manner to create variables, if not then how can i do it?
<?php
for(i=1;i<=10;i++){
$answer_+i=new array();
}
?>
Your PHP syntax is all wrong (Yes you missed some $s and added extra new). You can create them using following syntax. Its called variable variables
for($i=1;$i<=10;$i++){
${"answer_$i"} = array();
}
But I suggest you use array for this. Array is more convenient.
for($i=1;$i<=10;$i++){
$answer[$i] = array();
}
Here your $answer_1 will be $answer[1]. Best is to use no explicit index
for($i=1;$i<=10;$i++){
$answer[] = array();
}
Now $answer_1 will be $answer[0]. You can loop over it by for, foreach, can use a lot of array functions.
You can do it as stated in another answer, but usually the following is suited better:
<?php
$answers = array();
for($i=1;$i<=10;$i++){
$answers[]= array("blah", "123");
}
?>
So you can access answer #4 with:
<?php
$answers = array();
for($i=1;$i<=10;$i++){
$answers[]= array("blah", $i);
}
echo $answers[3] //array indexes start at 0!
?>
You should consider using a multidimensional array like:
$answers = array(
1 => array(),
2 => array()
);
... or ...
for($i=1;$i<=10;$i++)
$answers[$i] = array();

How to reference a item in an array numerically when it has been created as an associative array

I am using PHP 5.3.6
I have the following code below. Everything works fine except for the last line which attempts to to return a value based on the position in the array as opposed to the associative name. Can anyone explain why this takes place and how I can build the array so that I can reference an item either by the associative name or position number?
Thanks.
<?php
class myObject {
var $Property;
function myObject($property) {
$this->Property = $property;
}
}
$ListOfObjects['form_a'] = new myObject(1);
$ListOfObjects['form_b'] = new myObject(2);
$ListOfObjects['form_c'] = new myObject(3);
$ListOfObjects['form_d'] = new myObject(4);
echo "<pre>";
print_r($ListOfObjects);
echo "</pre>";
echo "<hr />";
foreach ($ListOfObjects as $key => $val) {
echo "<li>" . $ListOfObjects[$key]->Property . "</li>";
}
echo "<hr />";
echo "<li>" . $ListOfObjects['form_a']->Property . "</li>"; // Works ok.
//Edit: ------------------------------------------------------------
//Edit: Everything above is for context only
//Edit: I'm only interested in the line below and why it does not work
//Edit: ------------------------------------------------------------
echo "<li>" . $ListOfObjects[0]->Property . "</li>"; //Does not work.
?>
function value_from_index($a,$k){
return array_slice($a,$k,1);
}
If you just want the first/last element of an array, try end($array) for the last item without destroying it and reset($array) to get the first.
Don't use reset and end if you're looping through an array as Flambino notes, this indeed results in some unexpected behaviour.
For anything inbetween you'll need to use array_slice()
Not the nicest way of doing it, but effektive and readable:
$i = 0;
$last = count($ListOfObjects);
foreach($ListOfObjects as $obj) {
if($i == 0) {
//do something with first object
$obj->property;
else if ($i == ($last-1)) {
//do something with last object
$obj->property;
}
}
PHP arrays aren't like arrays you know from most other programming languages, they are more like ordered hash tables / ordered dictionaries - they allow for access by named index and retain order when new items are added. If you want to allow access with numeric indices to such an array you have to define it that way or use one of roundabout ways given in other answers.
In your case you can use a single line of code to allow access by index:
$ListOfObjects += array_values($ListOfObjects);
This will extend your array with the same one but with numeric indices. As objects are always passed by reference, you can access the same object by writing $ListOfObjects['form_b'] and $ListOfObjects[1].

Multiple Variable Variables in PHP

I am fairly new to PHP and programming in general... I am attempting to use a foreach loop to set some options on a page I have created. It all works except for the last section, where I am attempting to assign variables dynamically, so I can use them outside the loop.
<?PHP
$array=array(foo, bar, baz);
foreach ($array as $option) {
// I have if statements to determine what $option_req
// and $option_status end up being, they work correctly.
$option_req="Hello";
$option_status="World";
$rh='Req_';
$sh='Status_';
$$rh.$$option=$option_req;
$$sh.$$option=$option_status;
}
echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;
?>
When the loop is finished, should this now give me six variables?
$Req_foo
$Status_foo
$Req_bar
$Status_bar
$Req_baz
$Status_baz
I have played with this a bit, searches on Google seem fruitless today.
To access some array item, just access some array item.
No loops required.
$req = array("foo" => 1,
"bar" => 2,
"baz" => 3,
);
echo $req['foo'];
plain and simple
Looks like PHP doesn't like the concatenation when you're trying to do an assignment. Try doing so beforehand, like so:
<?php
$array = array('foo', 'bar', 'baz');
foreach ($array as $option)
{
$option_req="Hello";
$option_status="World";
$rh = 'Req_';
$sh = 'Status_';
$r_opt = $rh.$option;
$s_opt = $sh.$option;
$$r_opt = $option_req;
$$s_opt = $option_status;
}
echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;
As other commenters suggested, this isn't a great practice. Try storing your data in an array, rather than just cluttering up your namespace with variables.
You could (though you should not!) do:
${$rh.$option} = ...
Variable variables don't work that way. You need to have one variable containing the string.
$opt_r = $rh.$option;
$$opt_r = $option_req;
$opt_s = $sh.$option;
$$opt_s = $option_status;
Also, make sure to quote your strings:
$array=array('foo', 'bar', 'baz');
I don't suggest using variable variables, but if you want to, this is how to do it.

Categories