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.
I am working with a couple of arrays that are stored in sessions. The purpose is to be able to add and remove objects from the arrays which will contain recipients to messages posted. It SEEMS to be working okay but with some quirks.
This code allows objects to be added;
while($row = mysqli_fetch_array($result))
{
$contact = $row['contact'];
$userid = $row['userid'];
echo "<tr>";
echo "<td><a href='mypagepost.php?contact=$userid&recipient=$contact' STYLE='TEXT- DECORATION: NONE'><font color=#808080>" . $row['contact'] . "</a></font></td>";
echo "</tr>";
$contact_count++;
}
And this one gives me the ability to send to another page for removal from the respective arrays.
<?php
$isBefore = array();
foreach ($_SESSION['contactlist'] AS $key => $rec)
{
if (!in_array($rec, $isBefore)) {
$isBefore[] = $rec;
echo "<font color=#808080><a href='removerecipient.php?contact=" . $_SESSION['recipientlist'][$key] . "&recipient=$rec' STYLE='TEXT-DECORATION: NONE'>
<font color=#808080>" . $rec . " </a></font>";
}
}
?>
This references a page with the following;
unset($_SESSION['recipientlist'][array_search($contact, $_SESSION['recipientlist'])]);
unset($_SESSION['contactlist'][array_search($recipient, $_SESSION['contactlist'])]);
So, I'm just starting to learn how to use arrays effectively so please forgive me for asking an obtuse question or two. When I click on a recipient just once to add them to the arrays, it works fine. I find that I can click on recipients in a contact list multiple times and the array still allows them to be added over and over again (although it doesn't print them out in the list). When I go to remove them by clicking on their name, I have to click them over and over again until they're gone. How can I set up a situation where it only gets added once and that's it? The other question I have is that after I remove all recipients from an array, I'm still left with an index number with no value. The print looks like this for both arrays (this is after adding and removing three recipients from the list;
Array ( [3] => )
Array ( [3] => )
The indexes don't apear to have a value associated with them, no idea what this means.
You could create a $_SESSION and check to see
if(isset($_SESSION['nameHere'])){
//do your thing here
}
, or make a variable like
$varName = 0;
and when the form is submitted
if(isset($_POST['submitButtonName'])){
if($varName === 0){
$varName = 1;
//do you thing here
}
}
. That $_POST would be a $_GET if your <form method='get' in your HTML.
$icecream = array (
"Choco" => array('2 Dollars'),
"Mango" => array('3 Dollars')
);
print $icecream[0][0];
expected output:
2 Dollars
Edit: I have a huge list of icecream sorts and i do want to use a loop to output all the information as a HTML DOM. So I do not want to go through each array value and echo it with the explicit value (i.e. 'Choco', 'Orange', etc...).
I want to use values as keys for the "first array level" ($icecream[0]),
It does output nothing at all. What is my logical flaw with this solution?
try this:
echo $icecream['Choco'][0]
Your problem here is calling the wrong key for the 1st dim
.
.
For your updated question, try this:
$ice_k = array_keys($icecream);
echo $icecream[$ice_k[0]][0];
You're not using the associative array right. You need to use the right key.
echo $icecream['choco'][0];
You can use position but it will be a counter like this:
$counter = 0;
foreach($icecream As $k=>$v) {
echo $icecream[$k][0] . ' [' . $counter . ']';
$counter++;
}
and if you want to get only value you can use previous code
$ice_k = array_keys($icecream);
$position = 5;
if( isset($ice_k[$position]) ) {
echo $icecream[$ice_k[$position]][0];
}
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].
I'm developing a php app that uses a database class to query MySQL.
The class is here: http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/*note there are multiple bad practices demonstrated in the tutorial -- it should not be used as a modern guide!
I made some tweaks on the class to fit my needs, but there is a problem (maybe a stupid one).
When using select() it returns a multidimensional array that has rows with 3 associative columns (id, firstname, lastname):
Array
(
[0] => Array
(
[id] => 1
[firstname] => Firstname one
[lastname] => Lastname one
)
[1] => Array
(
[id] => 2
[firstname] => Firstname two
[lastname] => Lastname two
)
[2] => Array
(
[id] => 3
[firstname] => Firstname three
[lastname] => Lastname three
)
)
Now I want this array to be used as a mysql result (mysql_fetch_assoc()).
I know that it may be used with foreach(), but this is with simple/flat arrays. I think that I have to redeclare a new foreach() within each foreach(), but I think this could slow down or cause some higher server load.
So how to apply foreach() with this multidimensional array the simplest way?
You can use foreach here just fine.
foreach ($rows as $row) {
echo $row['id'];
echo $row['firstname'];
echo $row['lastname'];
}
I think you are used to accessing the data with numerical indices (such as $row[0]), but this is not necessary. We can use associative arrays to get the data we're after.
You can use array_walk_recursive:
array_walk_recursive($array, function ($item, $key) {
echo "$key holds $item\n";
});
With arrays in php, the foreach loop is always a pretty solution.
In this case it could be for example:
foreach($my_array as $number => $number_array)
{
foreach($number_array as $data = > $user_data)
{
print "Array number: $number, contains $data with $user_data. <br>";
}
}
This would have been a comment under Brad's answer, but I don't have a high enough reputation.
Recently I found that I needed the key of the multidimensional array too, i.e., it wasn't just an index for the array, in the foreach loop.
In order to achieve that, you could use something very similar to the accepted answer, but instead split the key and value as follows
foreach ($mda as $mdaKey => $mdaData) {
echo $mdaKey . ": " . $mdaData["value"];
}
Hope that helps someone.
Holla/Hello,
I got it! You can easily get the file name,tmp_name,file_size etc.So I will show you how to get file name with a line of code.
for ($i = 0 ; $i < count($files['name']); $i++) {
echo $files['name'][$i].'<br/>';
}
It is tested on my PC.
To get detail out of each value in a multidimensional array is quite straightforward once you have your array in place. So this is the array:
$example_array = array(
array('1','John','Smith'),
array('2','Dave','Jones'),
array('3','Bob','Williams')
);
Then use a foreach loop and have the array ran through like this:
foreach ($example_array as $value) {
echo $value[0]; //this will echo 1 on first cycle, 2 on second etc....
echo $value[1]; //this will echo John on first cycle, Dave on second etc....
echo $value[2]; //this will echo Smith on first cycle, Jones on second etc....
}
You can echo whatever you like around it to, so to echo into a table:
echo "<table>"
foreach ($example_array as $value) {
echo "<tr><td>" . $value[0] . "</td>";
echo "<td>" . $value[1] . "</td>";
echo "<td>" . $value[2] . "</td></tr>";
}
echo "</table>";
Should give you a table like this:
|1|John|Smith |
|2|Dave|Jones |
|3|Bob |Williams|
Example with mysql_fetch_assoc():
while ($row = mysql_fetch_assoc($result))
{
/* ... your stuff ...*/
}
In your case with foreach, with the $result array you get from select():
foreach ($result as $row)
{
/* ... your stuff ...*/
}
It's much like the same, with proper iteration.
Ideally a multidimensional array is usually an array of arrays so i figured declare an empty array, then create key and value pairs from the db result in a separate array, finally push each array created on iteration into the outer array. you can return the outer array in case this is a separate function call. Hope that helps
$response = array();
foreach ($res as $result) {
$elements = array("firstname" => $result[0], "subject_name" => $result[1]);
array_push($response, $elements);
}
I know this is quite an old answer.
Here is a faster solution without using foreach:
Use array_column
print_r(array_column($array, 'firstname')); #returns the value associated with that key 'firstname'
Also you can check before executing the above operation
if(array_key_exists('firstname', $array)){
print_r(array_column($array, 'firstname'));
}
Wouldn't a normal foreach basically yield the same result as a mysql_fetch_assoc in your case?
when using foreach on that array, you would get an array containing those three keys: 'id','firstname' and 'lastname'.
That should be the same as mysql_fetch_assoc would give (in a loop) for each row.
foreach ($parsed as $key=> $poke)
{
$insert = mysql_query("insert into soal
(pertanyaan, a, b, c, d, e, jawaban)
values
('$poke[question]',
'$poke[options][A]',
'$poke[options][B]',
'$poke[options][C]',
'$poke[options][D]',
'$poke[options][E]',
'$poke[answer]')");
}
If you need to do string manipulation on array elements, e.g, then using callback function array_walk_recursive (or even array_walk) works well. Both come in handy when dynamically writing SQL statements.
In this usage, I have this array with each element needing an appended comma and newline.
$some_array = [];
data in $some_array
0: "Some string in an array"
1: "Another string in an array"
Per php.net
If callback needs to be working with the actual values of the array,
specify the first parameter of callback as a reference. Then, any
changes made to those elements will be made in the original array
itself.
array_walk_recursive($some_array, function (&$value, $key) {
$value .= ",\n";
});
Result:
"Some string in an array,\n"
"Another string in an array,\n"
Here's the same concept using array_walk to prepend the database table name to the field.
$fields = [];
data in $fields:
0: "FirstName"
1: "LastName"
$tbl = "Employees"
array_walk($fields, 'prefixOnArray', $tbl.".");
function prefixOnArray(&$value, $key, $prefix) {
$value = $prefix.$value;
}
Result:
"Employees.FirstName"
"Employees.LastName"
I would be curious to know if performance is at issue over foreach, but for an array with a handful of elements, IMHO, it's hardly worth considering.
A mysql result set object is immediately iterable within a foreach(). This means that it is not necessary to call any kind of fetch*() function/method to access the row data in php. You can simply pass the result set object as the input value of the foreach().
Also, from PHP7.1, "array destructuring" allows you to create individual values (if desirable) within the foreach() declaration.
Non-exhaustive list of examples that all produce the same output: (PHPize Sandbox)
foreach ($mysqli->query("SELECT id, firstname, lastname FROM your_table") as $row) {
vprintf('%d: %s %s', $row);
}
foreach ($mysqli->query("SELECT * FROM your_table") as ['id' => $id, 'firstname' => $firstName, 'lastname' => $lastName]) {
printf('%d: %s %s', $id, $firstName, $lastName);
}
*note that you do not need to list all columns while destructuring -- only what you intend to access
$result = $mysqli->query("SELECT * FROM your_table");
foreach ($result as $row) {
echo "$row['id']: $row['firstname'] $row['lastname']";
}