[php] 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?

This question is related to php arrays echo

The answer is


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)
    )
);

function displayArrayValue($array,$key) {
   if (array_key_exists($key,$array)) echo "$key is at ".$array[$key];
}

displayArrayValue($page, "Service"); 

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

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'];

for the first question

$key = 'Home';
echo $key." is at ".$page[$key];

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;
}

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
)

array_walk($v, function(&$value, $key) {
   echo $key . '--'. $value;
 });

Learn more about array_walk


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.


You can try following code:

foreach ($arry as $key => $value) 
{
      echo $key;
      foreach ($value as  $val) 
      {
         echo $val; 
      }
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to echo

Multi-line string with extra space (preserved indentation) Bash: Echoing a echo command with a variable in bash Echo a blank (empty) line to the console from a Windows batch file Add php variable inside echo statement as href link address? How to format font style and color in echo How do I make a Windows batch script completely silent? Is there a php echo/print equivalent in javascript How to use css style in php How can I align the columns of tables in Bash? Double quotes within php script echo