Jump to content

[SOLVED] Arrays


Yesideez

Recommended Posts

<?php 
include 'db2.php';

$words = array ('apple', 'banjo', 'ceiling', 'duck', 'electric');

$long = array();

// add words and lengths to long array

foreach ($words as $w) {
    $long[] = array(
                    'len' => strlen($w),
                    'word' => $w
                );
}

// view the array

echo '<pre>', print_r($long, true), '</pre>';
?>

Link to comment
Share on other sites

This is a small sample of the output I received, how can I sort this list by the length of the word?

Array
(
    [0] => Array
        (
            [len] => 1
            [word] => A
        )

    [1] => Array
        (
            [len] => 3
            [word] => DAM
        )

    [2] => Array
        (
            [len] => 3
            [word] => ARK
        )

    [3] => Array
        (
            [len] => 4
            [word] => ZERO
        )

    [4] => Array
        (
            [len] => 3
            [word] => NOR
        )

    [5] => Array
        (
            [len] => 3
            [word] => OR
        )

Link to comment
Share on other sites

OK I'm really confused here now. Just reverse sorted the list using this:

<?php
  arsort($long);
?>
This is what I'm using to get the top 10 words in the list:
[code]<?php
  $topten="";
  for ($i=0;$i<10;$i++) {
    $topten.=$long[$i]['word'].'<br />';
  }
?>

This is what I'm getting returned:

A
DAM
ARK
ZERO
NOR
OR 
RE
ORZO 
ERR
ON

I'm confused that although the list shown using print_r has been sorted by the length of the word I can't figure out how to access the sorted data :([/code]

Link to comment
Share on other sites

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.