Giorgi Khachidze Giorgi Khachidze - 1 month ago 8
PHP Question

How to get a specific elemend from combined array?

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?

Answer

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".
?>
Comments