Prevent printing key indexes while printing the value - PHP - php

Hi I have an array like this:
array(
'Home' => array(
'About',
'Contact'
),
'News'
);
I wrote this to printing them:
function show($arr){
foreach($arr as $key => $value){
echo "\n<ul>\n<li>\n" . $key;
if( ! empty($value)){
if(is_array($value)){
show($value);
}else{
echo $value;
}
}
echo "\n</li>\n</ul>\n";
}
}
My problem is when I try to echo $value It'll print something like this:
Home
0About
1Contact
0News
I tried to echo $key where the echo $value is here now and I understood it's the key index which is gonna write before the News field or any field that is not an array. I fixed it with turning the single fields to this:
array(
'Home' => array(
'About' => **array()**,
'Contact' => **array()**
),
'News' => **array()**
);
But I don't want to define additional empty arrays!
Peace Out!

function show($arr){
foreach($arr as $key => $value){
echo "\n<ul>\n<li>";
if( ! empty($value)){
if(is_array($value)){
echo '\n'.$key;
show($value);
}else{
echo $value;
}
}
echo "\n</li>\n</ul>\n";
} }
I would say you have to change the place of you echo (of the $key). If it's not an array, you don't care about the key, right ?

function show($arr){
foreach($arr as $key => $value){
if (is_numeric($key))
echo "\n<ul>\n<li>\n";
else
echo "\n<ul>\n<li>\n" . $key;
if( ! empty($value)){
if(is_array($value)){
show($value);
}else{
echo $value;
}
}
echo "\n</li>\n</ul>\n";
}
}
I guess is_numeric should solve your problem.

Related

i run this code but it donot type the array

$studentArray = array(
array("ahmed2",15,3.5),
array("ahmed1",15,2.4),
array("ahmed3",29,3.9),
array("ahmed4",22,3),
array("ahmed5",23,2.8)
);
foreach($studentArray as $key => $value ){
echo $key. '-'.$value.'<br>';
}
Since you have student detail array in $studentArray, you need an extra foreach to loop through inner array.
Try below code in your structure.
$studentArray = array(
array("ahmed2",15,3.5),
array("ahmed1",15,2.4),
array("ahmed3",29,3.9),
array("ahmed4",22,3),
array("ahmed5",23,2.8)
);
foreach($studentArray as $studentDetail ){
foreach($studentDetail as $key => $value ){
echo $key. '-'.$value.'<br>';
}
}
For more better understanding, have a try with below code.
$studentArray = array(
array("val1"=>"ahmed2","val2"=>15,"val3"=>3.5),
array("val1"=>"ahmed1","val2"=>15,"val3"=>2.4),
array("val1"=>"ahmed3","val2"=>29,"val3"=>3.9),
array("val1"=>"ahmed4","val2"=>22,"val3"=>3),
array("val1"=>"ahmed5","val2"=>23,"val3"=>2.8)
);
foreach($studentArray as $student){
foreach($student as $key => $value) {
echo $key. '-'.$value.'<br>';
}
echo '<br>';
}

How can I get keys of a name attribute

I have this name="opt['.$id.']" value="'.$points.'" inside a checkbox input.Does anybody knows how I can get the $id?
UPDATED:
foreach($_POST['opt'] as $id => $value) {
$gift_ids = $value;
$gift_ids2 = implode(", ", $gift_ids);
}
echo $gift_ids2;
}
But I don't get any value on echo..
You need to iterate over the HTML array. Something like this should do it for you:
foreach($_POST['opt'] as $id => $value) {
Demo: https://eval.in/585379
your used array so you need to Iterate the $_POST['opt'] value
$_POST = array('opt' => array('1'=>100 ), 'eksasrgirwsh' => 'other');
foreach($_POST['opt'] as $id => $value)
{
echo $id //key example 1
echo $value //value example 100
}
If your $_POST is like this
$_POST = array('opt' => array('1'=>100 ), 'eksasrgirwsh' => 'other');
and you are giving $_POST['opt'] to foreach then your array for foreach is
$_POST['opt'] = array('1'=>100);
then you can't use implode in foreach because it give you an error. Do it without implode.
foreach($_POST['opt'] as $id => $value) {
$gift_ids = $value;
echo $gift_ids;
}

MultiDimensional arrays output

I am currently learning PHP and I am stuck with this problem while testing foreach with multi-dimensional arrays.
Here is my array:
$employees = array(
'Josh' => array(
'age'=>'55',
'salary'=>'105,000',
'hobbies'=> array('none')
),
'John' => array(
'age'=>'45',
'salary'=>'125,000',
'color'=>'red',
'hobbies'=> array('none')
),
'Jane' => array (
'age'=>'25',
'salary'=>'93,000',
'hobbies'=> array ('fishing', 'flying')
)
);
Whenever I try to output I always get an error of Array to string conversion or Invalid argument. Can somebody tell me how could I correctly output this multi-dimensional array using foreach?
If I do it this way, the data like 125,000, basically the value assigned to age and salary isn't written out.
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
echo $specifics.'<br>';
}
foreach($values as $hobbies) {
echo $hobbies;
}
}
If I do it this way, then it writes out, but as well it writes out "Array" and array to string error:
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
echo $specifics.$values.'<br>';
}
foreach($values as $hobbies) {
echo $hobbies;
}
}
Thanks.
Try following code
<?php
$employees = array(
'Josh' => array(
'age'=>'55',
'salary'=>'105,000',
'hobbies'=> array('none')
),
'John' => array(
'age'=>'45',
'salary'=>'125,000',
'color'=>'red',
'hobbies'=> array('none')
),
'Jane' => array (
'age'=>'25',
'salary'=>'93,000',
'hobbies'=> array ('fishing', 'flying')
)
);
foreach( $employees as $names_of_employees => $data ){
echo $names_of_employees.'<br>';
echo "Salary: ".$data['salary'].'<br>';
echo "Age: ".$data['age'].'<br>';
if( isset($data['hobbies']) && !empty($data['hobbies']) ) {
echo "Hobbies: ";
foreach( $data['hobbies'] as $hobbies ) {
echo $hobbies.'<br>';
}
}
}
Well, it depends on what you want.
foreach( $employees as $name => $data ){
echo $name;
echo $data['age'];
echo $data['salary'];
// ...etc...
}
It looks like for array element 'John' you've got an extra item in the second dimension. I believe this is ok in PHP but perhaps you have to account for this in the code you use to read the values out.
It is because you are trying to convert an array to a string. The problem is caused by hobbies since it is an array. So in your foreach loop that goes through $data you need to check if it is an array or if the key is equal to hobbies.
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
if(is_array($values)) { //or you could say if($specifics == 'hobbies')
echo $specifics . ': ' . implode(',',$values) . '<br>';
} else {
echo $specifics . ': ' . $values . '<br>';
}
}
}

traversing an array in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Loop an array of array
So I know how to traverse an array of even key => value (associative), but I have a weird array where I need to walk through it and print out values:
$object_array = array(
'type' => 'I am type',
array(
'property' => 'value',
'property_2' => 'value_2'
)
);
What I thought I could do is:
foreach($object as $key=>$vlaue){
//what now?
}
So as you can see I am lost, how do I walk through the next array?
You can try:
function traverse($array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
traverse($array);
continue;
}
echo $value;
}
}
foreach($object as $key=>$value){
if( is_array($value) ) {
foreach($value as $key2=>$value2) {
//stuff happens
}
} else {
//other stuff
]
}
Try:
foreach($object_array as $value) {
if(!is_array($value))
echo $value;
else {
foreach($value as $m)
echo $m;
}
}
Manual for foreach
In your for loop you could do:
if(is_array($object[$key]))
//process inner array here
It depends on how deep your arrays go, if you have arrays of arrays of arrays...and so on, a different method would be better, but if you just have one level this is a pretty simple way of doing it.
Well, you could do something like this:
foreach($object_array as $key=>$value)
{
if(is_array($value) {
foreach($value as $k=>$v) {
echo $k." - ".$v;
}
} else {
echo $key." - ".$value;
}
}
An alternative with array_walk_recursive():
function mydebug($value, $key) {
echo $key . ' => ' . $value . PHP_EOL;
}
array_walk_recursive($object_array, 'mydebug');
Handy if you doing something simple with the values (e.g. just echo ing).

echo key and value of an array without and with loop

This is an array i have
<?php
$page['Home']='index.html';
$page['Service']='services.html';
?>
How do i get to echo something like this for individual one like
Home is at index.html
and again how can i do this through a loop and echo all?
foreach($page as $key => $value) {
echo "$key is at $value";
}
For 'without loop' version I'll just ask "why?"
Without a loop, just for the kicks of it...
You can either convert the array to a non-associative one, by doing:
$page = array_values($page);
And then acessing each element by it's zero-based index:
echo $page[0]; // 'index.html'
echo $page[1]; // 'services.html'
Or you can use a slightly more complicated version:
$value = array_slice($page, 0, 1);
echo key($value); // Home
echo current($value); // index.html
$value = array_slice($page, 1, 1);
echo key($value); // Service
echo current($value); // services.html
If you must not use a loop (why?), you could use array_walk,
function printer($v, $k) {
echo "$k is at $v\n";
}
array_walk($page, "printer");
See http://www.ideone.com/aV5X6.
Echo key and value of an array without and with loop
$array = array(
'kk6NFKK'=>'name',
'nnbDDD'=>'claGg',
'nnbDDD'=>'kaoOPOP',
'nnbDDD'=>'JWIDE4',
'nnbDDD'=>'lopO'
);
print_r(each($array));
Output
Array
(
[1] => name
[value] => name
[0] => kk6NFKK
[key] => kk6NFKK
)
for the first question
$key = 'Home';
echo $key." is at ".$page[$key];
function displayArrayValue($array,$key) {
if (array_key_exists($key,$array)) echo "$key is at ".$array[$key];
}
displayArrayValue($page, "Service");
How to echo key and value of an array without and with loop
$keys = array_keys($page);
implode(',',$keys);
echo $keys[0].' is at '.$page['Home'];
My version without a loop would be like this:
echo implode(
"\n",
array_map(
function ($k, $v) {
return "$k is at $v";
},
array_keys($page),
array_values($page)
)
);
array_walk($v, function(&$value, $key) {
echo $key . '--'. $value;
});
Learn more about array_walk
A recursive function for a change;) I use it to output the media information for videos etc elements of which can use nested array / attributes.
function custom_print_array($arr = array()) {
$output = '';
foreach($arr as $key => $val) {
if(is_array($val)){
$output .= '<li><strong>' . ucwords(str_replace('_',' ', $key)) . ':</strong><ul class="children">' . custom_print_array($val) . '</ul>' . '</li>';
}
else {
$output .= '<li><strong>' . ucwords(str_replace('_',' ', $key)) . ':</strong> ' . $val . '</li>';
}
}
return $output;
}
You can try following code:
foreach ($arry as $key => $value)
{
echo $key;
foreach ($value as $val)
{
echo $val;
}
}

Categories