Jump to content

[SOLVED] Getting a single array key name and value name when the key is not known


sKunKbad

Recommended Posts

If I have an array with only one key => value pair, like this:

 

Array

(

    [black] => 5

)

 

 

I know I can use foreach to get the key and value, but since there is only one key=>value pair, and there will only ever be one key=>value pair, I was thinking there has to be a better way than using foreach. At first I thought that I should use [0], but that results in an undefined index. Should I just use foreach, or is there a better way to get both key and value.

I had tried using array_keys, but for some reason even after a second attempt, it still wouldn't work.

 

Using current() , which is something I've never used, worked great!

 

What kind of complicates things is that this array is inside an array, but it does work now:

 

<?php
// redirect if only one option
if (count($rates_array) == 1)
{
$ak = array_keys( $rates_array );
if( count( $rates_array[ $ak[0] ] ) == 1)
{
	$ak2 = $rates_array[ $ak[0] ];
	$_SESSION['checkout_data']['shipping_fee'] = current($ak2);
	$_SESSION['checkout_data']['shipping_type'] = array_search( current($ak2) , $ak2);
	header("Location: ".secure_base_url()."checkout/card_accept/one_ship".SITE_FILE_EXTENSION, TRUE, 302);
}
}

 

Thanks for your help!

Maybe I'm missing something obvious but you seem to be doing more work than might be necessary.  :shrug:

 

<?php
// redirect if only one option
if (count($rates_array) == 1)
{
$rate = current($rates_array);
if (count($rate) === 1)
{
	$_SESSION['checkout_data']['shipping_fee']  = current($rate);
	$_SESSION['checkout_data']['shipping_type'] = key($rate);
	header("Location: ".secure_base_url()."checkout/card_accept/one_ship".SITE_FILE_EXTENSION, TRUE, 302);
}
}

Maybe I'm missing something obvious but you seem to be doing more work than might be necessary.  :shrug:

 

The one and only Salathe I presume? I believe you have helped me, or been involved in discussions with me on Sitepoint and Kohana forums.

 

Yes, you are obviously correct. I was doing too much work. Oddly enough, in the 3.5 years I've been using php, I've never used current() or key(), so these functions are new to me. While I'm glad that I was able to solve my problem, I'm happy to have had my problem so I could learn something.

The one and only Salathe I presume? I believe you have helped me, or been involved in discussions with me on Sitepoint and Kohana forums.

One and the same, I get around a bit. :shy:

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.