Software | Support | Solutions

Blog

  • Multi-dimensional array fun with asort.

    Imagine you’re building a PHP application that manages a dictionary of terms, where each entry is stored in an associative array.

    The keys are unique lowercase strings (like single letters or identifiers), and the values are corresponding words or phrases (e.g., [“a” => “Apple”, “b” => “Banana”, “c” => “Cherry”]). Our task is to create a function that sorts this array by the values (the words) in either ascending (A to Z) or descending (Z to A) order, while preserving the original key-value associations.

    The function should also validate the sort order input to ensure it’s either “asc” or “desc”, throwing an error for invalid inputs.

    The Code

    Here’s the complete PHP function to achieve this:

    PHP

    <?php
    function sortArrayByValue(array $inputArray, string $sortOrder = 'asc'): array {
        // Validate sort order
        $validOrders = ['asc', 'desc'];
        if (!in_array(strtolower($sortOrder), $validOrders)) {
            throw new InvalidArgumentException("Sort order must be 'asc' or 'desc'");
        }
        
        // Create a copy to avoid modifying the original array
        $array = $inputArray;
        
        // Sort while maintaining index association
        if (strtolower($sortOrder) === 'asc') {
            asort($array, SORT_STRING);
        } else {
            arsort($array, SORT_STRING);
        }
        
        return $array;
    }
    ?>

    How It Works

    This function demonstrates key PHP sorting concepts, particularly for associative arrays. Let’s break it down step by step:

    1. Input Parameters:
      • $inputArray: This is the associative array you want to sort (e.g., [“a” => “Apple”, “b” => “Banana”]).
      • $sortOrder: A string indicating the sort direction, defaulting to ‘asc’. It accepts ‘asc’ for ascending or ‘desc’ for descending.
    2. Validation:
      • We convert $sortOrder to lowercase using strtolower() to make the check case-insensitive.
      • We use in_array() to verify if it’s one of the allowed values (‘asc’ or ‘desc’).
      • If invalid, it throws an InvalidArgumentException with a clear error message. This teaches good practice in input validation to prevent unexpected behavior.
    3. Copying the Array:
      • We create a copy of $inputArray to avoid modifying the original array passed by reference. This is important in PHP because arrays are passed by reference by default in functions.
    4. Sorting Logic:
      • For ascending order (‘asc’), we use asort($array, SORT_STRING).
        • asort() sorts the array by values while maintaining the key associations (unlike sort(), which reindexes numeric keys).
        • SORT_STRING ensures string comparison, treating values as strings (e.g., “Apple” comes before “Banana”).
      • For descending order (‘desc’), we use arsort($array, SORT_STRING).
        • arsort() works like asort() but in reverse order.
      • These functions sort in-place, modifying $array directly, which is why we made a copy earlier.
    5. Return Value:
      • The sorted array is returned, ready for use. The original keys remain intact, but the order of elements is now based on the sorted values.

    This highlights PHP’s built-in sort functions: asort() and arsort() are ideal for value-based sorting in associative arrays, preserving keys unlike ksort() (which sorts by keys) or sort() (which discards keys).

    Expected End Result

    Let’s test the function with an example array: $testArray = [‘c’ => ‘Cherry’, ‘a’ => ‘Apple’, ‘b’ => ‘Banana’]; (note the unsorted order).

    • Ascending Sort (sortArrayByValue($testArray, ‘asc’)):
      • Output: [‘a’ => ‘Apple’, ‘b’ => ‘Banana’, ‘c’ => ‘Cherry’]
      • Explanation: Values are sorted alphabetically (“Apple” first, then “Banana”, then “Cherry”), with keys preserved.
    • Descending Sort (sortArrayByValue($testArray, ‘desc’)):
      • Output: [‘c’ => ‘Cherry’, ‘b’ => ‘Banana’, ‘a’ => ‘Apple’]
      • Explanation: Values are sorted in reverse alphabetical order (“Cherry” first, then “Banana”, then “Apple”), keys intact.

    If you pass an invalid sort order like ‘random’, it throws: Error: Sort order must be ‘asc’ or ‘desc’.

    You can try this in a PHP environment (PHP 8.4 or compatible) by adding example usage code like in the commented section of the function.

  • Top 10 Technology Needs for Small Businesses in 2025

    As small businesses navigate an increasingly digital landscape, leveraging the right technologies can mean the difference between thriving and merely surviving. Here are the top 10 technology needs for businesses with 100 employees or fewer, along with practical solutions and supporting insights.

    1. Affordable Cybersecurity Solutions

    Small businesses are prime targets for cyberattacks due to their often-limited defenses. A report by the National Cyber Security Alliance found that 60% of small businesses that experience a cyberattack close within six months. Affordable options like cloud-based security platforms (e.g., Norton Small Business), password management tools (e.g., LastPass), and endpoint protection solutions (e.g., Bitdefender) can provide robust security without breaking the budget.

    2. User-Friendly AI Tools

    Artificial intelligence (AI) is no longer reserved for large enterprises. Small businesses can adopt tools like ChatGPT for customer service, Zoho Inventory for inventory management, and Mailchimp for marketing automation. According to a Salesforce report, 77% of small businesses believe AI can help them save time and improve efficiency, making it a critical investment.

    3. Cloud-Based Productivity Software

    With the rise of hybrid and remote work models, small teams need tools that enable seamless collaboration. Cloud-based solutions such as Google Workspace, Microsoft 365, and task management tools like Trello or Asana help small businesses stay organized and productive. According to Statista, 67% of small businesses rely on cloud-based productivity solutions to manage day-to-day operations.

    4. Website and E-Commerce Enhancements

    A strong online presence is vital for customer acquisition and retention. Platforms like Wix and Shopify enable small businesses to create professional websites and online stores quickly. SEO tools, such as Yoast SEO, and payment gateways like Stripe or Square can further enhance e-commerce capabilities. Research by BigCommerce shows that 96% of small businesses with online stores plan to increase their e-commerce investments.

    5. Affordable Automation Solutions

    Automation helps small businesses streamline repetitive tasks and focus on strategic priorities. Tools like HubSpot or Zoho CRM automate customer relationship management, while platforms like Zapier enable integrations between different apps to reduce manual work. A McKinsey study indicates that small businesses adopting automation experience a 20-30% increase in efficiency.

    6. Data Analytics for Decision-Making

    Data-driven decisions are essential for staying competitive. Affordable analytics tools such as Google Analytics, Tableau Public, and Power BI offer actionable insights into customer behavior, sales trends, and operational performance. A survey by Clutch found that 67% of small businesses leveraging analytics saw improved business outcomes.

    7. Mobile-First Tools

    Small business owners often operate on the go, making mobile-friendly tools indispensable. Mobile POS systems like Square or PayPal Here, scheduling apps like Calendly, and customer portals optimized for mobile use allow businesses to stay agile. According to Deloitte, mobile-first tools enhance operational flexibility and improve customer satisfaction.

    8. Digital Marketing Platforms

    Digital marketing levels the playing field for small businesses competing with larger brands. Tools like Canva simplify graphic design, Meta Ads enable targeted advertising, and email platforms like Mailchimp offer affordable ways to engage customers. HubSpot’s Small Business Marketing Report highlights that 72% of small businesses plan to increase digital marketing budgets in the coming year.

    9. Sustainability and Energy-Efficient Technology

    Customers increasingly prefer businesses with sustainable practices. Investing in energy-efficient equipment, adopting recycling solutions, and reducing paper use through digital operations can boost both reputation and efficiency. According to Forbes, 68% of small businesses are exploring green technologies to align with customer expectations and reduce costs.

    10. Cost-Effective IT Support

    Small businesses often lack the resources for an in-house IT team, making outsourced solutions critical. Managed Service Providers (MSPs) and subscription-based helpdesk services like GoTo Resolve or NerdsToGo offer affordable, scalable IT support. Research by TechRadar found that 43% of small businesses plan to increase their use of outsourced IT services in 2024.

    Final Thoughts

    These ten technology needs highlight the tools and strategies small businesses can leverage to stay competitive in a rapidly evolving market. By investing in cost-effective, scalable, and impactful solutions, small businesses can overcome challenges, enhance productivity, and achieve sustainable growth. Prioritizing these technologies will enable them to focus on what matters most—their customers and core operations.