Jump to content

Recommended Posts

I have an array I've created with keys and values as so:

 

$myArray["charley"] = "30";
$myArray["chris"] = "28";
$myArray["kate"] = "25";

 

I was wondering if there's any way to read keys & values from an array like this in a regular for loop somehow? I know how to use a foreach loop, but I want to use a for loop because I need to control how many items from my array appear on the page.

 

PS When I say for loop I mean something like:

 

for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

 

I just don't know the syntax of how to use an array with key / values in a for loop IF it's possible...

 

Thanks

 

FOO

Link to comment
https://forums.phpfreaks.com/topic/103994-array-key-value-in-a-for-loop/
Share on other sites

<?php
$myArray["charley"] = "30";
$myArray["chris"] = "28";
$myArray["kate"] = "25";
$key = array_keys($myArray);
for ($i = 0; $i < 3; $i++){
echo $myArray[$key[$i]],"<br />\n";
}
?>

 

Quick question - with this method I can access the value,  but what about the key? Perhaps I should use a regular array instead of key value pairs for what I'm trying to do...?

 

I have pairs of data I'd like to put in a single array - I need to somehow keep the pairs of data together - while maintaining a limit on the number of pairs of data I'll show on the page from the array.

 

Is there any other way to keep pairs of data together with arrays?

 

FOO

Hey Guys,

 

I just came up with one more question for you on this subject - I've tried using the sort function (http://www.php.net/sort) on my array and it seems to wipe out the key but retain the value.

 

Is there any way to sort my array by the value's and retain the keys? My value's will have names in them and I want to make sure they are in alphabetical order no matter where they are added in the array.

 

Thanks

 

FOO

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.