How to remove first element of an array using loop - php

I have very little experience with PHP, but I'm taking a class that has PHP review exercises. One of them is to create a function that uses a loop to return all values of an array except the first value in an unordered list. I'm assuming there's a way to do this using a foreach loop but cannot figure out how. This is what I had but I feel like I am far off:
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
$favColor = $array['favColor'];
$favMovie = $array['favMovie'];
$favBook = $array['favBook'];
$favWeb = $array['favWeb'];
echo '<h1>' . $myName . '</h1>';
function my_function() {
foreach($array == $myName){
echo '<ul>'
. '<li>' . $favColor . '</li>'
. '<li>' . $favMovie . '</li>'
. '<li>' . $favBook . '</li>'
. '<li>' . $favWeb . '</li>'
. '</ul>';
}
}
my_function();
?>

The correct syntax of foreach is
foreach (array_expression as $key => $value)
instead of
foreach($array == $myName){
function that uses a loop to return all values of an array except the
first value
I'm not sure, what exactly you mean by except the first value. If you are trying to remove first element from the array. Then you could have used array_shift
If you are supposed to use loop then
$count = 0;
foreach ($array as $key => $value)
{
if ($count!=0)
{
// your code
}
$count++;
}

Change the code to following
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
echo '<h1>' . $myName . '</h1>';
function my_function($array)
{
$count = 0;
echo "<ul>";
foreach($array as $key => $value)
{
if($key != "myName")
{
echo "<li>".$value."</li>";
}
}
echo "</ul>";
}
my_function($array);

Related

PHP - Duplicate <li>'s on foreach

i dont speak english but i will try get it.
My problems is on foreach ($json->mods->$k as $name) { because i'm getting duplicates <li>:
Heres the example:
<ul id="1">
<LI><B>BR:</B>
<LI><B>BR:</B>
<LI><B>BR:</B> Asterixmod, Explanado, Modquack</li>
<br>
<LI><B>DE:</B> Sweetphoenix</li>
<br>
<LI><B>E2:</B>
<LI><B>E2:</B> Irishcow, Welshnutter</li>
</ul>
CODE:
<?php
echo '<ul id="1">';
$link = '.json';
$f = file_get_contents($link);
$json = json_decode($f);
if (empty($json)) {
echo '<li id="ere"><B>ERROR</B></li>';
} else {
foreach ($json as $key => $val) {
foreach ($val as $k => $v) {
foreach ($json->mods->$k as $name) {
echo strtoupper('<li><b>' . $k . ':</b> ');
}
echo(implode(', ', $json->mods->$k));
echo '</li><br>';
}
}
echo '</ul>';
}
Hope anyone help me, ty.
The reason you're getting this error is because inside your foreach ($json->mods->$k as $name) you are opening an <li>, however, you're not closing it until after that loop. This means that eg. BR will have 3 opening tags and one closing tag.
Furthermore, you can get the output you want with just 1 loop:
foreach ($json->mods as $key => $val) {
echo '<li><b>' . strtoupper($key) . ':</b> ';
echo implode(', ', $val);
echo '</li><br>';
}
or you could even make the echo one line:
foreach ($json->mods as $key => $val) {
echo '<li><b>' . strtoupper($key) . ':</b> ' . implode(', ', $val) . '</li><br>';
}
Hope this helps!

How to "pause" a foreach loop to output few HTML lines

So let's say I have an array with key => values I want to output in 2 different HTML lists. Is it possible to do so by using the same loop?
<ul>
// Start foreach and get keys and values**
<li>$key</li>
// "Pause" foreach to output the next couple of lines once
</ul>
<ul>
// Resume foreach
<li>$value</li>
// End foreach
</ul>
The output should be
Key 1
Key 2
Key 3
Value 1
Value 2
Value 3
Think your looking for something like this:
<?php
$array = array("k1" => "v1", "k2" => "v2", "k3" => "v3");
$keys = "";
$values = "";
foreach($array as $k => $v) {
$keys .= "<li>" . $k . "</li>";
$values .= "<li>" . $v . "</li>";
}
echo "<ul>" . $keys . "</ul>";
echo "<ul>" . $values . "</ul>";
?>
Output:
k1
k2
k3
v1
v2
v3
you could use
array_chunk($array, 3, false); Then iterate through the sub_arrays into the differrnt lists
To iterate through the array :
foreach(**array_chunk($array, 3, false) as $container**){
echo '**<div><ul>**';
foreach($container as $val){
echo '<li> ' . $val[] . ' </li>';
}
echo "**</ul></div>**";
}

Php Multidimensional array for navigation

Needed Navigation Html
Home
Pages
About
Services
Products
Contact
FAQs
Sitemap
Privacy Policy
Column Layouts
1 Column
2 Column (Left Sidebar)
2 Column (Right Sidebar)
3 Column
4 Column
I want to use php arrays and foreach loops to output the needed html.
The php code I have thus far is:
<?php
$data = array("navigation");
$data['navigation']['Home'] = base_url();
$data['navigation']['Pages'] = base_url('pages');
$data['navigation']['Pages']['About'] = base_url('pages/about');
echo '<ul>';
foreach($data as $nav) {
foreach($nav as $subNavKey => $subNavHref) {
echo "<li><a href='$subNavHref'>$subNavKey</a>";
}
}
echo '</ul>';
?>
I was thinking I would need three foreach loops nested but php warnings/errors are generated when the third loop is reached on lines such as:
$data['navigation']['Home'] = base_url();
$data['navigation']['Pages'] = base_url('pages');
I'm not quite sure how to test for 3rd level depths such as:
$data['navigation']['Pages']['About'] = base_url('pages/about');
Also, outputting the needed li and ul tags in the proper positions has given me trouble aswell.
Use recursion
$data['navigation']['Home'] = base_url();
$data['navigation']['Pages'] = base_url('pages');
$data['navigation']['Pages']['About'] = base_url('pages/about');
$data['navigation']['Pages']['About']['Team'] = base_url('pages/team');
$data['navigation']['Pages']['About']['Team']['Nate'] = base_url('pages/nate');
echo "<ul>"
print_list($data);
echo "</ul>"
function print_list($menu) {
foreach($menu as $key=>$item) {
echo "<li>";
if(is_array($item)) {
echo "<ul>";
print_list($item);
echo "</ul>";
} else {
echo "<a href='{$val}'>$key</a>";
}
echo "</li>";
}
}
<?php
function nav($data) {
$html = '<ul>';
foreach ($data as $k => $v) {
if (is_array($v)) {
$html .= "<li>$k" . nav($v) . "</li>";
}
else {
$html .= "<li><a href='$k'>$v</a>";
}
}
$html .= '</ul>';
return $html;
}
echo nav($data);
A recursive function can get the job done:
$items = array(
"Home",
"Pages" => array(
"About",
"Services",
"Products",
"Contact",
"FAQs",
"Sitemap",
"Privacy Policy",
"Column Layouts" => array(
"1 Column",
"2 Column (Left Sidebar)",
"2 Column (Right Sidebar)",
"3 Column",
"4 Column"
)
)
);
function getMenu($array) {
foreach($array as $key => $value) {
if(is_array($value)) {
echo "<li>" . $key . "</li>";
echo "<ul>";
getMenu($value);
echo "</ul>";
} else {
echo "<li>" . $value . "</li>";
}
}
}
echo "<ul>";
getMenu($items);
echo "</ul>";
Output:
You should use a recursive function, for example (Working Demo):
function makeMenu($array)
{
$menu = '';
foreach($array as $key => $value) {
if(is_array($value)) {
$menu .= '<li>' . $key . '<ul>' . makeMenu($value) . '</ul></li>';
}
else {
$menu .= "<li><a href='". $value ."'>" . $value ."</a></li>";
}
}
return $menu;
}
Then call it like:
$data = array(
"Home",
"Pages" => array("About", "Services"),
"Column Layouts" => array("1 Column", "2 Column (Left Sidebar)")
);
echo '<ul>' . makeMenu($data) . '</ul>';

eliminate a specified post data on a post request array

I use this code to retrieve all the post request (refer below)
<?php
foreach ($_POST as $key => $value) {
$body .= $key . ": " . $value . '<br>';
}
echo $body;
?>
and there is a post data named "adminemail" and "cat", now what i want is to eliminate those two and print all the post data except those two. How to do that? any suggestions, recommendations and ideas, would love to hear. Thank you in advance.
option 1
unset($_POST['adminemail'],$_POST['cat']);
option 2
<?php
foreach ($_POST as $key => $value) {
if(!in_array($key,array('adminemail','cat'))){
$body .= $key . ": " . $value . '<br>';
}
}
echo $body;
?>
The following should work:
<?php
$arr = array_diff_key($_POST, array("adminemail" => 0, "cat" => 0));
$body = ""; // You must have this line, or PHP will throw an "Undefined variable" notice
foreach($arr as $key => $value){
$body .= $key . ": " . $value . "<br/>";
}
echo $body;
?>

PHP displaying multidimensional array

I have this array similar to this:
$suppliers = array(
'Utility Warehouse' => array('Gas' => array(0,0), 'Electricty' => array(0,0)),
'British Gas' => array('Gas' => array(93,124), 'Electricty' => array(93,124)),
'Eon' => array('Gas' => array(93,124), 'Electricty' => array(93,124))
);
How can display the information as follows
Utility Warehouse
Gas: 0-0 Electricity 0-0
British Gas
Gas: 93-134 Electricity: 93-134
Eon
Gas: 93-124 Electricity: 93-134
You can see how the displayed data corresponds to the data in the array. I've tried this:
foreach($suppliers as $a){
echo $a[0];
}
But this does nothing. CONFUSED!
<?php
foreach($suppliers as $supplier => $category) {
echo $supplier . '<br />';
foreach($category as $cat_name => $values_arr) {
echo $cat_name . ': ' . implode('-', $values_arr) . '<br /><br />';
}
}
?>
you can try:
foreach($suppliers as $name => $value) {
echo $name . "<br />";
foreach($value as $a => $price) {
echo $a .': '. $price[0].'-'.$price[1];
}
echo "<br /><br />";
}
The code to achieve what you want would be following, but i suggest you brush up on your PHP skills a bit more, as this is a trivial task.
foreach($suppliers as $name => $data){
echo $name . '<br/>';
foreach($data as $utility => $value){
echo $utility . ': ' . $value[0] . '-' . $value[1] . ' ';
}
echo '<br/><br/>';
}
Same answer as everyone else (I'm too slow). Here's a working example: http://codepad.org/PDPEjAGJ
Also, everyone who answered this question, me included, is guilty of spoonfeeding. Ahh well, the things I'll do for points! :p
Here is a simple recursive function one can use. I found it and modified it for presentation purposes. The original source is in the comments.
function print_a($array, $level=0){
# source: https://thisinterestsme.com/php-using-recursion-print-values-multidimensional-array/
foreach($array as $key => $value){
# If $value is an array.
if(is_array($value)){
echo str_repeat("-", $level). "<br>{$key}<br>\r\n";
# We need to loop through it.
print_a($value, $level + 1);
} else{
# It is not an array, so print it out.
echo str_repeat("-", $level) . "{$key}: {$value}<br>\r\n";
}
}
} # END FUNCTION print_a

Categories