0

I have something like this:

host1 | port1
host2 | port2
host3 | port3
host4 | port4

Now, I need to insert pairs into an array so I can use them in a loop:

I tried to loop through one value of an array

$hosts  = array('host1','host2','host3'); 

foreach ($hosts as $host) {

   echo $host;

}

How do I add pairs to an array so I can call say host it outputs both host and port?

4 Answers 4

3

You could create your array like this which creates named keys for each host:

$hosts = array(
    'host1' => 'port1',
    'host2' => 'port2',
    'host3' => 'port3'
);

(Example #1 here: http://www.php.net/manual/en/function.array.php)

You can then iterate through the array like so to grab the array key and value:

foreach($hosts as $host => $port){
    echo 'This is the ' . $host;
    echo 'This is the ' . $port;
}

(http://www.php.net/manual/en/control-structures.foreach.php)

Sign up to request clarification or add additional context in comments.

2 Comments

A small add to that, how can i do the same with three values in an array?
You can combine my answer with @Bill's and construct your array like this: $hosts = array('host1' => array('port1a', 'port1b')); You can then access the data in that array like so: echo $hosts['host1'][0]; // Will echo 'port1a'
2

You can use multidimensional array. Like this

$data= array
  (
  array("host1","yourport1"),
  array("host2","yourport2"),
  array("host3","yourport3"),
  );

and can access like this

echo "Host: ". $data[0][0]." Port: ".$data[0][1];

Comments

1

You could add arrays to the array, so you get an multidimensional array:

$hosts = array(array('host1', 'port1'), array('host2', 'port2'));

Comments

1

Fast way:

// also You can define it as string directly, but I think You have a file :)
foreach(explode(PHP_EOL,file_get_contents('myIP.txt')) as $line){
     $hosts[explode(' | ',$line)[0]] = explode(' | ',$line)[1];
}

var_dump($hosts); 

// You will have pairs host1 => port1, host2=>port2, etc

There's on more way with array_walk, but I'm too lazy to read docs about array_walk. Hope this solution will completly solve Your task

2 Comments

No, the data i need to add to an array is static, it never changes, something like config part of a PHP project to import later to other scripts...but thanks anyway for your answer
@skymario84 so You can define var like $myhosts = "host1 | port1 \r\n host2 | port2 \r\n"; and replace file_get_contents('myIP.txt') with $myhosts. It'll work. Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.