Riajul Islam
Riajul Islam

Reputation: 1485

How to convert array to string in cakephp

Here is my code

<?php
        rsort($max_k);
        for($i = 0; $i < 3; $i++) // Only loop 10 times.
        //echo $max_k[$i] . "<br>";
        $newArray = array_slice($max_k, 0, 10, true);

        echo ($newArray) ;

      ?>

Upvotes: 0

Views: 1048

Answers (3)

beta-developper
beta-developper

Reputation: 1774

Take advantage of Debugger Class

App::uses('Debugger','Utility');
$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13);
$arrayToString = Debugger::exportVar($array);
echo $arrayToString;

//Result:
//array( (int) 0 => (int) 1, (int) 1 => (int) 2, (int) 2 => (int) 3, (int) 3 => (int) 4, (int) 4 => (int) 5 )

link: http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::exportVar

Upvotes: 1

Volker
Volker

Reputation: 1

I used the following test code:

$max_k=array(1,2,3,4,5,6,7,8,9,10,11,12,13);
$newArray=array_slice($max_k, 0, 10, true);

In PHP you can produce a readable output from data structures in different ways. One of the oldest functions is print_r (php.net/manual/en/function.print-r.php):

print_r($newArray);

produces the output:

Array
(
  [0] => 1
  [1] => 2
  [2] => 3
  [3] => 4
  [4] => 5
  [5] => 6
  [6] => 7
  [7] => 8
  [8] => 9
  [9] => 10
)

The next possibility is var_dump (php.net/manual/en/function.var-dump.php), which takes one or more variables to display with value and structure:

var_dump($newArray);

One of my favourites is var_export (php.net/manual/en/function.var-export.php):

var_export($newArray);

which creates:

array (
  0 => 1,
  1 => 2,
  2 => 3,
  3 => 4,
  4 => 5,
  5 => 6,
  6 => 7,
  7 => 8,
  8 => 9,
  9 => 10,
)

Best feature of var_export is, that it supports a second boolean parameter. When set to true, it will return the readable version as a string. So you can for example log the output to a file instead of printing:

$output=var_export($newArray, true);
print $output;

Result:

array (
  0 => 1,
  1 => 2,
  2 => 3,
  3 => 4,
  4 => 5,
  5 => 6,
  6 => 7,
  7 => 8,
  8 => 9,
  9 => 10,
)

Hope that helps.

PS: The php.net site has a cool feature: if you enter a search string after the php.net like:

php.net/var_dump

you will be sent to the man page of that function, if it exists or see a list of similar results, if there is no function with that name :)

Upvotes: 0

Prakhar Agrawal
Prakhar Agrawal

Reputation: 1022

Please try using print_r($newArray)

you may use foreach() for accessing individual elements as needed according to your program logic. Hope this is enough for the task. Do comment if you need anything else.

Upvotes: 0

Related Questions