0

I have two arrays, then i combines them with array_combine() method and now i want to get a secend elemont of new array in thic case: Ben = 37

<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
$a = $c[1];
?>

but it outputs erros Notice: Undefined offset: 1 Have i made a mistake? Yep but where?

Ghhihihihih
  • 27
  • 1
  • 7
  • The keys of your *combined* array would be `Peter`,`Ben` and `Joe`, not `0`, `1`, etc. Do `var_dump($c);` to see the array structure. – Rajdeep Paul Oct 20 '16 at 18:24
  • [Did you try to print out the contents of `$c`? If you did you'd know that there's no `1` key](https://eval.in/663927). – h2ooooooo Oct 20 '16 at 18:25
  • 1
    Why did you use `array_combine()` in the first place, if you want to access elements by number? Do you understand what it does? – Barmar Oct 20 '16 at 18:30
  • Thanks and when i want to acces and get kay and alos value? – Giorgi Khachidze 18 secs ago For example how can i get: Ben = 37 – Ghhihihihih Oct 20 '16 at 18:47

3 Answers3

2

After combine you got an associative array, where the second element is not "1" but "Ben" :

<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
//$a = $c[1];
$a = $c["Ben"];  // KEY="Ben", VALUE="37".
echo $a;
?>

Edit #1 : get key "Ben" and its value :

<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);

$keys = array_keys( $c );
echo $keys[ 1 ] .    // "Ben"
     "=" .
     $c[ $keys[1] ]; // "37".
?>
2

array_combine uses the first parameter as keys and the second as values. so it goes to the result:

Array ( 
    [Peter] => 35 
    [Ben] => 37 
    [Joe] => 43 
)

So you can access the age with the name as key.

$a = $c['Peter']; // 35
jmattheis
  • 10,494
  • 11
  • 46
  • 58
1
<?php
   $fname=array("Peter","Ben","Joe");
   $age=array("35","37","43");
   $c=array_combine($fname,$age);
   $a = $c['Ben'];

?>
Jeff
  • 283
  • 1
  • 8