Меню

Array to string conversion php ошибка

What the PHP Notice means and how to reproduce it:

If you send a PHP array into a function that expects a string like: echo or print, then the PHP interpreter will convert your array to the literal string Array, throw this Notice and keep going. For example:

php> print(array(1,2,3))

PHP Notice:  Array to string conversion in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(591) :
eval()'d code on line 1
Array

In this case, the function print dumps the literal string: Array to stdout and then logs the Notice to stderr and keeps going.

Another example in a PHP script:

<?php
    $stuff = array(1,2,3);
    print $stuff;  //PHP Notice:  Array to string conversion in yourfile on line 3
?>

Correction 1: use foreach loop to access array elements

http://php.net/foreach

$stuff = array(1,2,3);
foreach ($stuff as $value) {
    echo $value, "n";
}

Prints:

1
2
3

Or along with array keys

$stuff = array('name' => 'Joe', 'email' => 'joe@example.com');
foreach ($stuff as $key => $value) {
    echo "$key: $valuen";
}

Prints:

name: Joe
email: joe@example.com

Note that array elements could be arrays as well. In this case either use foreach again or access this inner array elements using array syntax, e.g. $row['name']

Correction 2: Joining all the cells in the array together:

In case it’s just a plain 1-demensional array, you can simply join all the cells into a string using a delimiter:

<?php
    $stuff = array(1,2,3);
    print implode(", ", $stuff);    //prints 1, 2, 3
    print join(',', $stuff);        //prints 1,2,3

Correction 3: Stringify an array with complex structure:

In case your array has a complex structure but you need to convert it to a string anyway, then use http://php.net/json_encode

$stuff = array('name' => 'Joe', 'email' => 'joe@example.com');
print json_encode($stuff);

Prints

{"name":"Joe","email":"joe@example.com"}

A quick peek into array structure: use the builtin php functions

If you want just to inspect the array contents for the debugging purpose, use one of the following functions. Keep in mind that var_dump is most informative of them and thus usually being preferred for the purpose

  • http://php.net/print_r
  • http://php.net/var_dump
  • http://php.net/var_export

examples

$stuff = array(1,2,3);
print_r($stuff);
$stuff = array(3,4,5);
var_dump($stuff);

Prints:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(4)
  [2]=>
  int(5)
}

This is a short PHP guide on how to fix the “Array to string conversion” error. This is a common notice that appears whenever you attempt to treat an array like a string.

Reproducing the error.

To reproduce this error, you can run the following code:

//Simple PHP array.
$array = array(1, 2, 3);

//Attempt to print the array.
echo $array;

The code above will result in the following error:

Notice: Array to string conversion in C:wampwwwtestindex.php on line 7

On the page, you will also see that the word “Array” has been printed out.

This error occurred because I attempted to print out the array using the echo statement. The echo statement can be used to output strings or scalar values. However, in the example above, we made the mistake of trying to ‘echo out’ an array variable.

To fix this particular error, we would need to loop through the array like so:

//Simple PHP array.
$array = array(1, 2, 3);

//Loop through the elements.
foreach($array as $value){
    //Print the element out.
    echo $value, '<br>';
}

We could also implode the array into a comma-delimited string like so:

//Simple PHP array.
$array = array(1, 2, 3);

//Implode the array and echo it out.
echo implode(', ', $array);

Either approach will work.

The main thing to understand here is that you cannot treat an array like a string. If you attempt to do so, PHP will display a notice.

Multidimensional arrays.

Multidimensional arrays can also cause problems if you are not careful. Take the following example:

//Basic multidimensional array.
$array = array(
    1,
    2,
    array(
        1, 2
    )
);

//Loop through the array.
foreach($array as $val){
    //Print out the element.
    echo $val, '<br>';
}

In the code above, we attempt to print out each element in our array. The problem here is that the third element in our array is an array itself. The first two iterations of the loop will work just fine because the first two elements are integers. However, the last iteration will result in a “Array to string conversion” error.

To solve this particular error, we can add a simple check before attempting to output each element:

//Loop through the array.
foreach($array as $val){
    //Print out the element if it isn't an array.
    if(!is_array($val)){
        echo $val, '<br>';
    }
}

In the code above, we used the PHP function is_array to check whether the current element is an array or not.

We could also use a recursive approach if we need to print out the values of all sub arrays.

Debugging arrays.

If this error occurred before you were trying to see what is inside a particular array, then you can use the print_r function instead:

echo '<pre>';
print_r($array);
echo '</pre>';

Alternatively, you can use the var_dump function:

//var_dump the array
var_dump($array);

Personally, I think that using the var_dump function (combined with X-Debug) is the best approach as it provides you with more information about the array and its elements.

Printing out a PHP array for JavaScript.

If you are looking to pass your PHP array to JavaScript, then you can use the json_encode function like so:

//Basic multidimensional array.
$array = array(
    1,
    2,
    array(
        1, 2
    )
);

//Format the PHP array into a JSON string.
echo json_encode($array);

The PHP snippet above will output the array as a JSON string, which can then be parsed by your JavaScript code. For more information on this, you can check out my article on Printing out JSON with PHP.

Conclusion.

As stated above, the “Array to string conversion” notice will only appear if your PHP code attempts to treat an array variable as if it is a string variable. To avoid this, you must either modify the logic of your application or check the variable type.

  John Mwaniki /   13 Dec 2021

When working with arrays in PHP, you are likely to encounter the «Notice: Array to string conversion» error at some point.

This error occurs when you attempt to print out an array as a string using the echo or print.

Example 1

<?php
$person = array("first_name" => "John", "last_name" => "Doe","age" => 30, "gender" => "male");
echo $person;

Output

Notice: Array to string conversion in /path/to/file/filename.php on line 3
Array

Example 2

<?php
$myarray = array(30, 28, 25, 35, 20, 27, 40, 36);
print $myarray;

Output

Notice: Array to string conversion in /path/to/file/filename.php on line 3
Array

PHP echo and print are aliases of each other and used to do the same thing; output data on the screen.

The echo and print statements are used to output strings or scalar values (a single value that is not an array eg. string, integer, or a floating-point), but not arrays.

When you try to use echo or print on an array, the PHP interpreter will convert your array to a literal string Array, then throw the Notice for «Array to string conversion».

Never treat an array as a string when outputting its data on the screen, else PHP will always display a notice.

If you are not sure whether the value of a variable is an array or not, you can always use the PHP inbuilt is_array() function. It returns true if whatever is passed to it as an argument is an array, and false if otherwise.

Example

<?php
//Example 1
$variable1 = array(30, 28, 25, 35, 20, 27, 40, 36);
echo is_array($variable1);
//Output: 1

//Example 2
$variable2 = "Hello World!";
echo is_array($variable2);
//Output:

In our two examples above, we have two variables one with an array value, and the other a string value. On passing both to the is_array() function, the first echos 1, and the second prints nothing. This suggests that the first is an array while the second is not.

Solutions to «Array to string conversion» notice

Below are several different ways in which you can prevent this error from happening in your program.

1. Use of the is_array() function

Since the error occurs as a result of using echo or print statements on an array, you can first validate if the variable carries an array value before attempting to print it. This way, you only echo/print it when you are absolutely sure that it is not an array.

Example

<?php
//Example 1
$variable1 = array(30, 28, 25, 35, 20, 27, 40, 36);
if(!is_array($variable1)){
  echo $variable1;
}
else{
  echo "Variable1 has an array value";
}
//Output: Variable1 has an array value

//Example 2
$variable2 = "Hello World!";
if(!is_array($variable2)){
  echo $variable2;
}
else{
  echo "Variable2 has an array value";
}
//Output: Hello World!

This eliminates any chances of the array to string conversion happening.

2. Use var_dump() or print_r() function

These functions work almost exactly the same way, in that they all print the information about a variable and its value.

The var_dump() function is used to dump information about a variable. It displays structured information of the argument/variable passed such as the type and value of the given variable.

The print_r() function is also a built-in function in PHP used to print or display information stored in a variable.

Example 1

<?php
$person = array("first_name" => "John", "last_name" => "Doe","age" => 30, "gender" => "male");
echo var_dump($person);

Output:

array(4) { [«first_name»]=> string(4) «John» [«last_name»]=> string(3) «Doe» [«age»]=> int(30) [«gender»]=> string(4) «male» }

Example 2

<?php
$person = array("first_name" => "John", "last_name" => "Doe","age" => 30, "gender" => "male");
echo print_r($person);

Output:

Array ( [first_name] => John [last_name] => Doe [age] => 30 [gender] => male ) 1

With either of these functions, you are able to see all the information you need about a variable.

3. Use the array keys or indices to print out array elements

This should be the best solution as it enables you to extract values of array elements and print them out individually.

All you have to do is to use an index or a key of an element to access to print out its value.

Example 1

Using array keys to get the array elements values.

<?php
$person = array("first_name" => "John", "last_name" => "Doe","age" => 30, "gender" => "male");
echo "First Name: ".$person["first_name"]."<br>";
echo "Last Name: ".$person["last_name"]."<br>";
echo "Age: ".$person["age"]."<br>";
echo "Gender: ".$person["gender"];

Output:

First Name: John
Last Name: Doe
Age: 30
Gender: male

Example 2

Using array indices to get the array elements values.

<?php
$cars = array("Toyota", "Audi", "Nissan", "Tesla", "Mazda", "BMW");
echo $cars[0]."<br>";
echo $cars[1]."<br>";
echo $cars[2]."<br>";
echo $cars[3]."<br>";
echo $cars[4]."<br>";
echo $cars[5];

Output:

Toyota
Audi
Nissan
Tesla
Mazda
BMW

However, if you are not sure about the type of data stored in the variable prior to printing it, you don’t have a choice but to use either is_array(), var_dump() and print_r(). These will enable you to know whether the variable is an array, and if so, its structure. You will know the array keys, indices, and the array’s depth (if some of the array elements have arrays as their values).

4. Use the foreach() loop to access the array elements

You can iterate through the array elements using the foreach() function and echo each element’s value.

<?php
$cars = array("Toyota", "Audi", "Nissan", "Tesla", "Mazda", "BMW");
foreach ($cars as $car) {
    echo $car."<br>";
}

Output:

Toyota
Audi
Nissan
Tesla
Mazda
BMW

Or for associative arrays, use key-value pairs to access the array elements.

<?php
$person = array("first_name" => "John", "last_name" => "Doe","age" => 30, "gender" => "male");
foreach ($person as $key => $value) {
    echo "$key: $value<br>";
}

Output:

first_name: John
last_name: Doe
age: 30
gender: male

This works perfectly well for 1-dimensional arrays. However, if the array is a multidimensional array, the same notice error of «Array to string conversion» may be experienced. A multidimensional array is an array containing one or more arrays.

In such a case, either use the foreach loop again or access these inner array elements using array syntax (keys or indices), e.g. $row[‘name’].

5. Stringify the array into a JSON string with json_encode()

You can use the built-in PHP json_encode() function to convert an array into a JSON string and echo it using echo or print statement.

Example 1

<?php
$person = array("first_name" => "John", "last_name" => "Doe","age" => 30, "gender" => "male");
echo json_encode($person);

Output:

{«first_name»:»John»,»last_name»:»Doe»,»age»:30,»gender»:»male»}

Example 2

<?php
$cars = array("Toyota", "Audi", "Nissan", "Tesla", "Mazda", "BMW");
echo json_encode($cars);

Output:

[«Toyota»,»Audi»,»Nissan»,»Tesla»,»Mazda»,»BMW»]

6. Convert the array to a string using implode() function

The implode() function returns a string from the elements of an array.

Syntax

implode(separator,array)

This function accepts its parameters in either order. However, it is recommended to always use the above order.

The separator is an optional parameter that specifies what to put between the array elements. Its default value is an empty string, ie. «».

The array is a mandatory parameter that specifies the array to join into a string.

Using this method as a solution to print an array is best applicable for 1-dimensional arrays.

Example

<?php
$cars = array("Toyota", "Audi", "Nissan", "Tesla", "Mazda", "BMW");
echo implode(", ", $cars);

Output:

Toyota, Audi, Nissan, Tesla, Mazda, BMW

That’s all for this article.

It’s my hope you found it useful, and that it has helped you solve your problem. Have an awesome coding time.

In this article, we will take a look at the Array to string conversion error in PHP and try to solve it. This error comes when we try to print array variable as a string using the built-in PHP function print() or echo.

Example

// Declare a PHP array
$myarray = array(1,2,3,4,5,6,7,7);
// Print PHP array using echo and print() functions.
echo $myarray;
print($myarray);

Output

Notice: Array to string conversion in phpprint.php on line 8
Array
Notice: Array to string conversion in phpprint.php on line 9
Array

The error is encountered here as the code tries to print the array called myarray like a string. As the echo and print statement is used for printing strings values and scalar values, so when they are not able to treat an array variable as a string.    

Solution

The easiest solution to this problem is to mention the index values along with the echo and print statement. When you type $myarray[2] or $myarray[3], echo and print will be able to recognize it as an array and then display the values.

For example,

$myarray = array(1,2,3,4,5,6,7,7);
// Print PHP array using echo and print() functions.
echo $myarray[2];
print($myarray[0]);   

 The five ways to solve this error are as follows:

  1. Using Builtin PHP Function print_r
  2. Using Built-in PHP Function var_dump
  3. Using PHP Inbuilt Function implode() to Convert Array to String
  4. Using Foreach Loop to Print Element of an Array
  5. Using the json_encode Method

Solution 1: Using Builtin PHP Function print_r

// Declare a PHP array
$myarray = array(1,2,3,4,5,6,7,7);
// Print PHP array using print_r() functions.
print_r($myarray);

Output

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

Here, the print_r method takes the parameter $myarray and prints its values in the form of keys and values. The keys here are the indexes and the values are the elements in those index positions.   

Solution 2: Using Built-in PHP Function var_dump

// Declare a PHP array
$myarray = array(1,2,3,4,5,6,7,7);
// Print PHP array using print_r() functions.
var_dump($myarray);

Output

array(8) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [5]=> int(6) [6]=> int(7) [7]=> int(7) }

Here, the var_dump method takes the parameter $myarray and prints out the type and the structured information about that variable. It first displays the type of the variable, which is an array in this case. Then it prints the elements in the form of key and value pairs as shown below.   

Solution 3: Using PHP Inbuilt Function implode() to Convert Array to String

// Declare a PHP array
$myarray = array(1,2,3,4,5,6,7,7);
// Convert array to string by using implode function.
$arraydata = implode(',',$myarray);
echo $arraydata;

Output

1,2,3,4,5,6,7,7

In this code, the implode() method is used. This method returns a string after accepting an array of elements as input. Here, the method is passed ‘,’ as the separator and $myarray as the array argument. So, the method takes the array and converts its elements into a string and joins them using a ‘,’ separator.  

Solution 4: Using Foreach Loop to Print Element of an Array

// Declare a PHP array
$myarray = array(1,2,3,4,5,6,7,7);
// run foreach loop to every element of array.
foreach($myarray as $ma){
echo $ma . '<br>';
}

Output

1

2

3

4

5

6

7

7

Here, the foreach loop is used for iterating over the array of elements in $myarray. Then the elements are printed out one by one with a line break after every element, specified by <br>

Solution 5: Using the json_encode Method

The json_encode method takes a JSON encoded string and converts it to a PHP variable. You can use this method to convert an array into a string. For example,

<?php
$myarray = array(2,4,6);
print json_encode($myarray);

Output

[2,4,6]

Conclusion

As we have discussed above, the Array to string conversion occurs when your PHP code tries to handle an array variable like a string. The best way to avoid this is to alter the logic of your code or check the type of the variable you are trying to convert.    

All the above examples are used for printing the value of an array. But if you want to use the value of the array for some operation, you can use for each function.

Во первых ты пытаешься file_get_contents() от объекта $file. Эта функция на вход хочет строку.
Возможно у твоего обьекта file есть какой-нибудь arrayAccess или __toString() почему-то возвращающий массив

$arrayFiles[] = (StorageFactory::make('minio'))->store($file->getClientOriginalName(), file_get_contents($file));

Может как-то так
file_get_contents($file->getClientFilePath())

функцию getClientFilePath() я с потолка взял. Она не имеет смысла кстати. Путь на клиенте тебе не доступен для чтения. Если это файл отправляемый пользователем там будет что-то $file->getTmpPath(), куда он временно закачался для твоего скрипта и откуда исчезнет если ничего не сделать. И там будет не file_get_contents() а какой-нибудь copy($file->getTmpPath(), $new_location);

Второй код ничего не говорит и даже не вызывает твой $arrayFiles никак не привязан

Что до $response, то если в нем $arrayFiles; то сделать «echo Array()» нельзя без такой ошибки. Сначала Array() нужно конвертировать в строку с помощью json_encode() или там serialize() или другим способом

За последние 24 часа нас посетили 9267 программистов и 863 робота. Сейчас ищет 371 программист …


  1. tyshka

    tyshka
    Активный пользователь

    С нами с:
    4 фев 2015
    Сообщения:
    21
    Симпатии:
    0

    Notice: Array to string conversion in
    Notice: Undefined property: PanelGenerator::$Array in
    Fatal error: Uncaught Error: Function name must be a string in

    указывается строка

    1. $out .= $this->$option[‘type’]( $option );

    используется эта строка в foreach

    var_dump( $options );
    var_dump( $option );

    показывает что данные не пустые

    1. foreach( $options as $option ) {
    2.     $out .= $this->$option[‘type’]( $option );

    в PHP5 все работает отлично


  2. [vs]

    Команда форума
    Модератор

    С нами с:
    27 сен 2007
    Сообщения:
    10.534
    Симпатии:
    623

    // Ванга-мод ON

    1. $out .= $this->{$option[‘type’]}( $option );

    // OFF


  3. tyshka

    tyshka
    Активный пользователь

    С нами с:
    4 фев 2015
    Сообщения:
    21
    Симпатии:
    0


  4. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

    А почему работает, поняли? Это очень важно.


  5. tyshka

    tyshka
    Активный пользователь

    С нами с:
    4 фев 2015
    Сообщения:
    21
    Симпатии:
    0


  6. mahmuzar

    @tyshka, нельзя обращаться с массивом как с строкой.


  7. tyshka

    tyshka
    Активный пользователь

    С нами с:
    4 фев 2015
    Сообщения:
    21
    Симпатии:
    0

    почему в php5 не было ошибки, а в php7 это уже фатальная ошибка?


  8. mahmuzar

    @tyshka, не знаю почему работало в php 5, но заключается в фигурные скобки для обработки значения массива. Т.е. выше без скобок тебе передавался массив, а заключив в фигурные скобки переменная обработалась как надо, в итоге получил переменную. Это сложный синтаксис обработки переменных.
    — Добавлено —
    http://php.net/manual/ru/language.types.string — пункт «обработка переменных».


  9. tyshka

    tyshka
    Активный пользователь

    С нами с:
    4 фев 2015
    Сообщения:
    21
    Симпатии:
    0

    Видимо потому что работало в php 5 это и вызвало мое замешательство… Спасибо всем ответившим!


  10. [vs]

    Команда форума
    Модератор

    С нами с:
    27 сен 2007
    Сообщения:
    10.534
    Симпатии:
    623

    @tyshka в PHP7 изменён парсер в целях ускорения. Теперь переменная разбирается строго слева направо. Таким образом, получается $this — объект, $option — имя свойства объекта, [‘type’] — элемент массива в свойстве, () — вызов функции с именем-строкой из этого элемента массива объекта.
    Поскольку option — это массив, по правилам приведения типов он превращается в слово Array с выбрасыванием ошибки. У $this нет такого свойства нет, соответственно имя функции оказывается null и получается Fatal. Подробно в доке http://bit.ly/2inWjSy

    Теперь надо привыкать к следующей логике:

    1.   public $names = [‘One’ => ‘Fn’];
    2.   public function run($arrName) {
    3.     $this->$arrName[‘One’]();

    — Добавлено —
    В PHP 5 будет


    denis01 и mahmuzar нравится это.


  11. tyshka

    tyshka
    Активный пользователь

    С нами с:
    4 фев 2015
    Сообщения:
    21
    Симпатии:
    0


  12. mahmuzar

    @[vs], объяснил хорошо, пример несколько запутанный дал, это специально?))


  13. [vs]

    Команда форума
    Модератор

    С нами с:
    27 сен 2007
    Сообщения:
    10.534
    Симпатии:
    623

    @mahmuzar мне кажется, этот пример воспроизводит ситуацию ТС. На PHP5 в фнукцию run() можно передать массив [‘One’=>’Fn’] и ожидать, что это приведет к вызову $this->fn().


  14. denis01

    Команда форума
    Модератор


  15. mahmuzar

    @[vs], просто fn() вне класса.
    — Добавлено —
    @[vs],@denis01, теперь понял, до меня не сразу дошло, что ты предполагал.


  16. opalko

    С нами с:
    2 ноя 2021
    Сообщения:
    1
    Симпатии:
    0

    Как это побороть? Ошибки

    PHP Notice: Array to string conversion in

    В коде

    1.    <a href=»<?php echo ${‘sort_’ . $field}; ?>» class=»<?php echo ($sort == ${‘sort_’ . $field}) ? strtolower($order) : »; ?>» title=»<?php echo ${‘text_’ . $field}; ?>»><i class=»fa fa-image fa-2x»></i></a>

    и
    В коде

    1.    <a href=»<?php echo ${‘sort_’ . $field}; ?>» class=»<?php echo ($sort == ${‘sort_’ . $field}) ? strtolower($order) : »; ?>»><?php echo ${‘text_’ . $field}; ?></a>

Если вам потребовалось преобразовать массив php в строку, то для этого есть несколько инструментов. Применение того или иного инструмента зависит от ваших целей.

Если вы ищете как решить проблему «PHP Notice: Array to string conversion in …», то это значит, что вы, в каком-то месте вашего кода используете массив, но обрабатываете его как строку.

Например:

$array = [1,2,3];
echo $array; // Notice

Вы получите «Notice» в строке echo $array, поскольку функция echo предназначеня для вывода строк, а не массивов.

Теперь поговорим о конвертации массива в строку:

1. Функция implode()

С ее помощью можно «склеить» элементы массива в строку, через любой разделитель. Подробнее: implode
Пример:

echo implode('|', array(1, 2, 3)); // выдаст строку: 1|2|3

Подобным образом мы можем преобразовать только одномерные массивы и у нас пропадут ключи.

У этой функции есть антагонист explode , который наоборот преобразует строку в массив по разделителю.

2. Функция join()

Работает точно так же как и implode(), поскольку это просто псевдоним, выбирайте название, которое больше нравится.

Пример у нас будет идентичный:

echo join('|', array(1, 2, 3)); // выдаст строку: 1|2|3

3. Функция serialize()

Основная задача функции — преобразование переменной (в нашем случае массива) в состояние пригодное для хранения.
Она используется для сохранения массива в строку, для ее последующего преобразования обратно в массив. Вы можете сохранить массив в файл или базу данных, а затем, при следующем выполнении скрипта восстановить его.
Подробнее: serialize

Пример:

$array = array( '1' => 'elem 1', '2'=> 'elem 2', '3' => 'elem 3');
$string = serialize($array); 
echo $string; // выдаст строку: a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}

Затем из этой строки, можно снова получить массив:

$array = unserialize($string);

4. Функция json_encode()

Возвращает JSON представление данных.
В нашем случае, данная функция, напоминает сериализацию, но JSON в основном используется для передачи данных. Вам придется использовать этот формат для обмена данными с javascript, на фронтенде. Подробнее: json_encode

Пример

$array = array(
    1 => 'one',
    2 => 'two',
);

$json = json_encode($array);

echo $json; // {"1":"one","2":"two"}

Обратная функция json_decode() вернет объект с типом stdClass, если вторым параметром функции будет false. Либо вернет ассоциативный массив, если передать true вторым параметром

5. Функция print_r

Она подходит для отладки вашего кода. Например вам нужно вывести массив на экран, чтобы понять, какие элементы он содержит.

 $array = [
    'param1' => 'val1',
    'param2' => 'val2',
];
				
print_r($array);

/* выводит на экран:
Array
(
    [param1] => val1
    [param2] => val2
)
*/

6. Функция var_dump

Функция var_dump также пригодится для отладки. Она может работать не только с массивами, но и с любыми другими переменными, содержимое которых вы хотите проверить.

$array = [
    'param1' => 'val1',
    'param2' => 'val2',
];
				
var_dump($array);

/* выводит на экран:
array(2) { ["param1"]=> string(4) "val1" ["param2"]=> string(4) "val2" } 
*/

7. Функция var_export

Эта функция преобразует массив интерпритируемое значение, которое вы можете использовать для объявление этого массива. Иными словами, результат этой функции — програмный код.

$array = [
    'param1' => 'val1',
    'param2' => 'val2',
];
				
var_export($array);

/* выводит на экран:
array ( 'param1' => 'val1', 'param2' => 'val2', )
*/

Обратите внимание, что функции print_r, var_dump, var_export выводят результат сразу на экран. Это может быть удобно, т.к. эти функции все равно используются в основном для отладки, но при желании вы можете записать результат их выполнения в переменную. Для print_r и var_export для этого нужно установить второй параметр в true:

$result1 = print_r($array, true);
$result2 = var_export($array, true);

var_dump не возвращает значение, но при желании это конечно можно сделать через буферизацию.

array_to_string

Как таковой функции array_to_string в php нет, но есть описанные выше инструменты, которых более чем достаточно для выполнения задачи. Я просто хотел напомнить, что вы никогда не ограничены этими инструментами, и можете написать то, что подходит именно под вашу задачу.

function array_to_string($array) {
    ob_start();
    var_dump($array);
    return ob_get_clean();
}

Как сделать работу с массивами еще проще?

Если вы используете библиотеку для работы с коллекциями, то ваш код для преобразования массива в строку может выглядеть куда более изящно:

echo collect(['a', 'b', 'c'])->implode(','); // a,b,c

echo collect(['a', 'b', 'c'])->toJson(); // ["a","b","c"]

Также рекомендую обратить внимание на полезную библиотеку для работы со строками. С ее помощью вы можете выполнять операции со строками более удобно и с меньшим количеством кода.

На этом все. Обязательно прочитайте справку по данным функциям и пишите если у вас остались вопросы.

Нашли опечатку или ошибку? Выделите её и нажмите Ctrl+Enter

Помогла ли Вам эта статья?

Когда у вас есть много входов HTML с именем C[] то в массиве POST на другом конце вы получаете массив этих значений в $_POST['C'] . Итак, когда вы echo this, вы пытаетесь распечатать массив, поэтому все, что он делает, это печатает Array и уведомление.

Чтобы правильно распечатать массив, вы либо просматриваете его в цикле и каждый элемент echo , либо можете использовать print_r .

В качестве альтернативы, если вы не знаете, массив это или строка или что-то еще, вы можете использовать var_dump($var) который сообщит вам, что это за тип и каково его содержимое. Используйте это только для целей отладки.

Что означает уведомление PHP и как его воспроизвести:

Если вы отправляете массив PHP в функцию, которая ожидает строку вида: echo или print , тогда интерпретатор PHP преобразует ваш массив в буквальную строку Array , бросьте это Обратите внимание и продолжайте идти. Например:

php> print(array(1,2,3))

PHP Notice:  Array to string conversion in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(591) :
eval()'d code on line 1
Array

В этом случае функция print выгружает буквальную строку: Array в stdout, а затем записывает уведомление в stderr и продолжает работу.

Другой пример в сценарии PHP:

<?php
    $stuff = array(1,2,3);
    print $stuff;  //PHP Notice:  Array to string conversion in yourfile on line 3
?>

Исправление 1: используйте цикл foreach для доступа к элементам массива

http://php.net/foreach

$stuff = array(1,2,3);
foreach ($stuff as $value) {
    echo $value, "n";
}

Печать:

1
2
3

Или вместе с ключами массива

$stuff = array('name' => 'Joe', 'email' => '[email protected]');
foreach ($stuff as $key => $value) {
    echo "$key: $valuen";
}

Печать:

name: Joe
email: [email protected]

Обратите внимание, что элементы массива также могут быть массивами. В этом случае либо снова используйте foreach либо обращайтесь к этим элементам внутреннего массива, используя синтаксис массива, например $row['name']

Исправление 2: объединение всех ячеек в массиве вместе:

В случае, если это простой одномерный массив, вы можете просто объединить все ячейки в строку, используя разделитель:

<?php
    $stuff = array(1,2,3);
    print implode(", ", $stuff);    //prints 1, 2, 3
    print join(',', $stuff);        //prints 1,2,3

Исправление 3: преобразовать массив в массив со сложной структурой:

Если ваш массив имеет сложную структуру, но вам все равно нужно преобразовать его в строку, используйте http://php.net/json_encode

$stuff = array('name' => 'Joe', 'email' => '[email protected]');
print json_encode($stuff);

Печать

{"name":"Joe","email":"[email protected]"}

Быстрый взгляд на структуру массива: используйте встроенные функции php

Если вы хотите просто проверить содержимое массива с целью отладки, используйте одну из следующих функций. Имейте в виду, что var_dump является наиболее информативным из них и поэтому обычно предпочтительнее для этой цели.

  • http://php.net/print_r
  • http://php.net/var_dump
  • http://php.net/var_export

Примеры

$stuff = array(1,2,3);
print_r($stuff);
$stuff = array(3,4,5);
var_dump($stuff);

Печать:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(4)
  [2]=>
  int(5)
}

Вы используете <input name='C[]' в своем HTML. Это создает массив в PHP при отправке формы.

Вы используете echo $_POST['C']; чтобы отобразить этот массив — это не сработает, а вместо этого выдаст это уведомление и слово «Массив».

В зависимости от того, что вы сделали с остальной частью кода, вам, вероятно, следует использовать echo $_POST['C'][0];

Array to string conversion в последних версиях php 7.x является ошибкой, а не предупреждением, и предотвращает дальнейшее выполнение кода.

Использование print , echo в массиве больше не является вариантом.

Подавление ошибок и уведомлений не является хорошей практикой, особенно в среде разработки и все еще отлаживает код.

Используйте var_dump , print_r , перебирайте входное значение с помощью foreach или for для вывода входных данных для имен, объявленных как входные массивы (‘ name[] ‘)

Наиболее распространенной практикой для обнаружения ошибок является использование блоков try/catch , которые помогают нам предотвратить прерывание выполнения кода, которое может вызвать возможные ошибки, заключенные в блок try .

  try{  //wrap around possible cause of error or notice
    
    if(!empty($_POST['C'])){
        echo $_POST['C'];
    }

  }catch(Exception $e){

    //handle the error message $e->getMessage();
  }

<?php
ob_start();
var_dump($_POST['C']);
$result = ob_get_clean();
?>

если вы хотите зафиксировать результат в переменной

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Array initializer expected java ошибка
  • Ariston avsf 129 ошибка f 12