Skip to content

Instantly share code, notes, and snippets.

@naoxink

naoxink/print_array.php

Last active Jul 17, 2018
Embed
What would you like to do?
print_array PHP
<?php
/**
* Imprime un array en consola con otro formato
* @param array $array
* @param integer $lvl
* @param integer $keylen
* @param integer $actual_spaces
*/
function print_array($array, $lvl = 0, $keylen = 0, $actual_spaces = 0){
if($lvl == 0){
echo "Array:\n";
}
$root = ' |';
$spaces = str_repeat(' ', $actual_spaces + $keylen);
$dashes = str_repeat('—', $keylen);
$total_space = $actual_spaces + $keylen*2;
foreach ($array as $key => $value) {
if(is_array($value)){
echo $spaces . ' |' . $dashes . ' ' . $key . "\n";
print_array($value, $lvl + 1, 2, $total_space);
}else{
if($lvl > 0){
echo $spaces . $root . $dashes . ' ';
}else{
echo $root . ' ';
}
$type = gettype($value);
if($type == 'boolean'){
$value = $value ? 'true' : 'false';
}elseif ($type == 'string') {
$value = '"'. $value .'"';
}
echo $key .' → (' .$type. ') '. $value . "\n";
}
}
}
/*
Uso:
$a = array(
'lvl1' => array(
'test1' => true,
'test2' => array(
'arrayNormal1',
'arrayNormal2',
'arrayNormal3',
'arrayNormal4'
),
'probando una key larga' => 'muahahahaha',
'y otra key muy larga a ver si sale en cuenca' => array(array(1,2), 2, 3, 4, 5)
),
'key1' => 1,
'randomNumber' => rand(),
'string' => 'Hola',
'emptyString' => ''
);
print_array($a);
Resultado:
Array:
| lvl1
|-- test1 -> (boolean) true
|-- test2
|-- 0 -> (string) "arrayNormal1"
|-- 1 -> (string) "arrayNormal2"
|-- 2 -> (string) "arrayNormal3"
|-- 3 -> (string) "arrayNormal4"
|-- probando una key larga -> (string) "muahahahaha"
|-- y otra key muy larga a ver si sale en cuenca
|-- 0
|-- 0 -> (integer) 1
|-- 1 -> (integer) 2
|-- 1 -> (integer) 2
|-- 2 -> (integer) 3
|-- 3 -> (integer) 4
|-- 4 -> (integer) 5
| key1 -> (integer) 1
| randomNumber -> (integer) 1499064065
| string -> (string) "Hola"
| emptyString -> (string) ""
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.