For loop in php code needs an explanation - php

<!-- 1- create a new file called lab3.php
2- add the HTML skeleton code and give its title “Lab Week 3”
3- open up an php scope
4- Create an associative array listing favourite subjects. (example: math, english, science and grade for each A+ B+ C- )
5- print out for grade english subject
6- using a for loop print all the items in the array
-->
>
<?php
//Code for associative array
//data for associated array
$subjects = [
"math" => "A+",
"english" => "B+",
"science" => "C-",
]
<br>
// Code to print out english grade
//print out for english grade
echo "My grade in english class is" . $subjects["english"];
<br>
// This is my for loop section. If anyone could help me figure this out I'd be greatly appreciated.
//print out all the items in the array using for loop
for ($x=0; <= 2){
echo "$subjects[$x]";
}
?>

For all the items in your array use foreach instead:
foreach ($subjects as $subject => $grade) {
echo 'My grade in '.$subject. ' is '. $grade . PHP_EOL;
}
BTW: 1. Don't forget to remove <br> tags in your php code.
You cannot use for loop here, since your array does not have numeric array keys, and if you run for loop in the way you showed in your code, you will get undefined array key warnings.
Try it online!

Related

Foreach data list from array - incrementing numbers

I am trying to create a option list from a JSON decoded API link.
So far I have the access to the API sorted, all the data I need stored in a single variable and can extract data from the variable using
print_r($result[0]["ORGANISATION_NAME"]);
print_r($result[1]["ORGANISATION_NAME"]);
This will give me two different Organisation names from the array.
What I would like to do is put this in an alphabetical drop down menu, but for some reason I cannot for the life of me get foreach to work. All we need to do is increment the 0,1,2,3 etc to the number of records stored in the database.
I have no idea on how to do that !
To answer your question as asked:
foreach ($results as $result) {
for ($i = 0; $i < count($result); $i++) {
print_r($result[$i]["ORGANISATION_NAME"]);
}
}
However, why not just another foreach?
EDIT:
Updating based off of new info:
Assuming $result is your DB result here is your new code:
foreach ($result as $row) {
print_r($row['ORGANISATION_NAME']);
}
I think a couple of sensible steps of data preparation will help to simplify this task for you.
Isolate the desired column of data and create a new 1-dimensional array of organization names.
Sort the names alphabetically.
Then you can use a simple foreach loop to generate the html select field.
Code (Demo)
$result = [
["ORGANISATION_NAME" => "B Name"],
["ORGANISATION_NAME" => "D Name"],
["ORGANISATION_NAME" => "C Name"],
["ORGANISATION_NAME" => "A Name"]
];
echo "Proof of correct structure: {$result[1]["ORGANISATION_NAME"]}\n";
$org_names = array_column($result, "ORGANISATION_NAME");
sort($org_names);
var_export($org_names); // display alphabetized array
echo "\n---\n";
echo "<select name=\"orgs\">";
foreach ($org_names as $org) {
echo "<option>$org</option>";
}
echo "</select>";
Output:
Proof of correct structure: D Name
array (
0 => 'A Name',
1 => 'B Name',
2 => 'C Name',
3 => 'D Name',
)
---
<select name="orgs">
<option>A Name</option>
<option>B Name</option>
<option>C Name</option>
<option>D Name</option>
</select>

Get Records From Array Based On Value

Bottom line, I have a huge multidimensional array returned by ldap_get_entries that I am trying to parse into different groups based on the location attribute.
In PowerShell I could do something like:
$location1 = Get-ADUser -Filter * | ? {?_.l -eq "test_location"}
What I am currently doing within PHP (as far as my brain will let me go) is something like:
Foreach ($records as $record) {
if (isset($record['l'])) {
switch ($record['l'][0]) {
case "test_location1":
$location1[] = $record;
continue 2;
case "test_location2":
$location2[] = $record;
continue 2;
}
}
}
I then use a foreach loop (alternative syntax) against an array of location variables ($location1, $location2), that I used the above method, to sort records into their appropriate location variable. In this way, I build an HTML table grouping each locations records together. I build a new table for each location with some HTML code in between each group, so I don't believe sorting the ldap results by location will work, as it would output one large table.
Is there any way to specify a WHERE clause in PHP? So that I can assign all records in an array with a matching key value to variable1 and all records in an array with a different matching key value to variable2.
I am assuming I am tackling this in an amateur scripting way.. If there is an easier way to accomplish this task (maybe skipping the assign records to variables part), or any sort of "best practice" I am missing here, I am up for learning it.
Thanks in advance!!
As far as I understood your question you want something like this:
$recordsSorted = array();
foreach ($records as $record) {
if (! isset($record['l'])) {
continue;
}
$recordsSorted[$records['l'][0]][] = $record;
}
ksort($recordsSorted);
foreach($recordsSorted as $location => $records) {
usort($records, function($a, $b){
return strnatcasecmp($a['uid'][0], $b['uid'][0]);
});
echo '<h1>$location</h1><ul>';
foreach ($records as $record) {
echo '<li>' . $record['dn'] . '</li>';
}
echo '</ul>';
}
This will first put the first entry to the location-attribute of an entry as key of an array. That key can then be used to sort the array.
To output the content then it iterates over the new array and sorts the content - in this case using the first value of the uid-attribute (change the uid to whatever attribute you need). This sorted content is then output to HTML.
the first array $recordsSorted might look somewhat like this:
array(
'London' => array(
array(<entry from the LDAP>),
array(<another entry from LDAP>),
),
'Paris' => array(
array(<a further entry from the LDAP>),
),
'Berlin' => array(
array(<and even another entry from the LDAP>),
),
);
The result would then look somewhat like this:
<h1>Berlin</h1>
<ul>
<li>[UID of and even another entry from the LDAP]</li>
</ul>
<h1>London</h1>
<ul>
<li>[UID of another entry from LDAP]</li>
<li>[UID of entry from the LDAP]</li>
</ul>
<h1>Paris</h1>
<ul>
<li>[UID of a further entry from the LDAP]</li>
</ul>
Does that look like it could help you?

codeigniter input tag attribute

Can anyone explain, how this cat array is getting the id and name?
foreach ($all_categories as $menu) { ?>
<input type="checkbox" id="cat_<?php echo $menu->id; ?>" value="<?php echo $menu->id.'_'.$menu->name; ?>" name="cat[]">
..
..
}
and i can get the id and name in controller,by using like below. It is working totally fine. My question is, how id went to cat array in position 0,and name position 1?
$res_arr=explode('_',$value);
$cat_id=$res_arr[0];
$cat_name=$res_arr[1];
The explode function returns an array either it finds the delimiter or not. You gave a string to explode and asked it to split the string wherever it sees '_'. So in your case there was only one '_' and explode sliced the string into two pieces and placed them in an array respectively at [0] and [1].
Edit:
<?php
foreach ($all_categories as $menu) {
print "<input type=\"checkbox\" id=\"cat_".$menu->id."\" value=\"".$menu->id."_".$menu->name."\" name=\"cat[]\"/>";
}
?>
php short tag is not recommended Link

PHP - using foreach with array

I'm struggling to get the correct syntax to to parse out the values from an array to use with the foreach loop. I have an array:
$contacts_array
which contains one or more names which I need to search on. The array looks like this:
Array
(
[0] => PR1010
[1] => PR1086
)
If I was to manually generate the required PHP code with a known number of names it would look like this where there are 2 names to search on:
// Create first find request
$findreq1 =$fm->newFindRequest('Contacts');
// Create second find request
$findreq2 =$fm->newFindRequest('Contacts');
// Specify search criterion for first find request
$findreq1->addFindCriterion('Name', $searchTerm);
// Specify search criterion for second find request
$findreq2->addFindCriterion('Suburb', $searchTerm);;
// Add find requests to compound find command
$request->add(1,$findreq1);
$request->add(2,$findreq2);
I need to generate the equivalent code for every name in the array. I know I need to use something like:
foreach($contacts_array as $contact_array => $value)
{
}
as well as:
$num = 1
$num++; } /* foreach record */
I'm just not sure how to bring this all together so that it increments the $findreq1 variables as I go. All my attempts so far generate errors. If anyone can show me how to combine this together that would be greatly appreciated as I'm learning PHP as I go.
Thanks
<?php
for($i = 0; $i < count($contacts_array); $i++) {
${'findreq' . ($i+1)} = $fm->newFindRequest('Contacts');
${'findreq' . ($i+1)}->addFindCriterion('Name', $contacts_array[$i]);
$request->add($i+1, ${'findreq' . ($i+1)});
}
?>
Read more about Dynamic variable names in PHP
You guys beat me to it.
<?php
$contacts = Array('PR1010','PR1086');
//print_r($contacts);
foreach ($contacts as $key => $value) {
//echo "key: ".$key." - Value: ".$value."<br>";
$findreq1 = $fm->newFindRequest('Contacts');
$findreq1->addFindCriterion('Name', $value); // this is where the Array's value is passed too, it is looped for every value in the Array
$request->add(1,$findreq1);
// do more here
}
?>

PHP Session Array Value keeps showing as "Array"

When sending data from a form to a second page, the value of the session is always with the name "Array" insteed of the expected number.
The data should get displayed in a table, but insteed of example 1, 2, 3 , 4 i get : Array, Array, Array.
(A 2-Dimensional Table is used)
Is the following code below a proper way to "call" upon the stored values on the 2nd page from the array ?
$test1 = $_SESSION["table"][0];
$test2 = $_SESSION["table"][1];
$test3 = $_SESSION["table"][2];
$test4 = $_SESSION["table"][3];
$test5 = $_SESSION["table"][4];
What exactly is this, and how can i fix this?
Is it some sort of override that needs to happen?
Best Regards.
You don't need any sort of override. The script is printing "Array" rather than a value, because you're trying to print to the screen a whole array, rather than a value within an array for example:
$some_array = array('0','1','2','3');
echo $some_array; //this will print out "Array"
echo $some_array[0]; //this will print "0"
print_r($some_array); //this will list all values within the array. Try it out!
print_r() is not useful for production code, because its ugly; however, for testing purposes it can keep you from pulling your hair out over nested arrays.
It's perfectly fine to access elements in your array by index: $some_array[2]
if you want it in a table you might do something like this:
<table>
<tr>
for($i = 0 ; $i < count($some_array) ; $i++) {
echo '<td>'.$some_array[$i].'</td>';
}
</tr>
</table>
As noted, try
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
That should show you what's in the session array.
A 2-dimensional table is just an array of arrays.
So, by pulling out $_SESSION["table"][0], you're pulling out an array that represents the first row of the table.
If you want a specific value from that table, you need to pass the second index, too. i.e. $_SESSION["table"][0][0]
Or you could just be lazy and do $table = $_SESSION["table"]; at which point $table would be your normal table again.
A nice way ...
<?php
foreach ($_SESSION as $key => $value) {
echo $key . " => " . $value . "<br>";
}
?>

Categories