edgarmtze
edgarmtze

Reputation: 25038

key and value array access in php

I am calling a function like:

get(array('id_person' => $person, 'ot' => $ot  ));

In function How can I access the key and value as they are variable?

function get($where=array()) {

  echo where[0];
  echo where[1];
}

How to extract 'id_person' => $person, 'ot' => $ot without using foreach as I know how many key-values pairs I have inside function?

Upvotes: 0

Views: 284

Answers (4)

sectus
sectus

Reputation: 15454

If you do not care about keys and want to use array as ordered array you can shift it.

function get($where=array()) {
$value1 = array_shift($where);
$value2 = array_shift($where);
}

Upvotes: 0

jszobody
jszobody

Reputation: 28911

Couple ways. If you know what keys to expect, you can directly address $where['id_person']; Or you can extract them as local variables:

function get($where=array()) {
   extract($where);
   echo $id_person;
}

If you don't know what to expect, just loop through them:

foreach($where AS $key => $value) {
    echo "I found $key which is $value!";
}

Upvotes: 1

Erica Xu
Erica Xu

Reputation: 555

Just do $where['id_person'] and $where['ot'] like you do in JavaScript.

Upvotes: 0

kero
kero

Reputation: 10638

You can access them via $where['id_person'] / $where['ot'] if you know that they will always have these keys.

If you want to access the first and second element, you can do it like this

reset($where)
$first = current($where);
$second = next($where);

Upvotes: 1

Related Questions