Search code examples
php

increase integer and use it as array key with some prefix : Unsupported operand types: string + int


This is my code:

$dns = ['host'=>['mynewcomp2','www']];

foreach($dns as $i=>$dn){
        $j=$i+1;
        $args['HostName'.$j] = $dns['host'][$i];
}

I get error when I want to increase $i and use it as array key with some prefix

Uncaught TypeError: Unsupported operand types: string + int

The error is in this line: $j=$i+1;

I need the result like this:

$args['HostName1'] = $dns['host'][0];
$args['HostName2'] = $dns['host'][1];

Solution

  • If you want to get the list of HOSTS then you have to extract this list and then browse it. In your example you browse a list of DNS and not the list of HOSTS.

    // Initialization
    $dns    = ['host'=>['mynewcomp2','www']];
    $args   = array();
    
    // Extraction
    $hosts  = $dns['host'];
    
    // Construction Array
    foreach($hosts as $key => $value)   $args["HostName".($key+1).""] = $value;
    
    // Display
    echo "<pre>"; print_r($args); echo "</pre>";