Author: Pooja Kotwani

  • Operators in Objective C

    The Objective-C language, built on top of C, retains many of the same operators as C. These operators are crucial for creating mathematical expressions and performing various operations. Operators act on variables (operands) to produce a result. For example, in the expression c = a + b, the + and = are operators, and ab, and c are operands.

    Objective-C is widely used for developing iOS and macOS applications. The operators can be categorized as follows:

    Types of Operators

    1. Arithmetic Operators: Arithmetic operators perform basic mathematical operations on operands, such as addition, subtraction, multiplication, and division.

    OperatorDescriptionExample
    +Adds two operandsc = a + b; // c = 12
    -Subtracts second operand from the firstc = a - b; // c = -2
    *Multiplies two operandsc = a * b; // c = 35
    /Divides numerator by denominatorc = a / b; // c = 4
    %Returns remainder of divisionc = a % b; // c = 0
    ++Increments operand by 1a++; // a = 6
    --Decrements operand by 1a--; // a = 5

    Example:

    #import <Foundation/Foundation.h>
    
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        int n1 = 5, n2 = 3;
        NSLog(@"ADDITION = %d", (n1 + n2));
        NSLog(@"SUBTRACTION = %d", (n1 - n2));
        NSLog(@"MULTIPLICATION = %d", (n1 * n2));
        NSLog(@"DIVISION = %d", (n1 / n2));
        NSLog(@"MODULUS = %d", (n1 % n2));
    
        [pool drain];
        return 0;
    }

    Output:

    ADDITION = 8
    SUBTRACTION = 2
    MULTIPLICATION = 15
    DIVISION = 1
    MODULUS = 2

    2. Relational (Comparison) Operators: Relational operators compare two values, returning true or false based on the comparison.

    OperatorDescriptionExample
    ==Checks if two operands are equal(a == b) // false
    !=Checks if two operands are not equal(a != b) // true
    >Checks if left operand is greater(a > b) // true
    <Checks if left operand is smaller(a < b) // false
    >=Checks if left operand is greater or equal(a >= b) // true
    <=Checks if left operand is smaller or equal(a <= b) // false

    Example:

    #import <Foundation/Foundation.h>
    
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        int n1 = 5, n2 = 3;
        NSLog(@"ADDITION = %d", (n1 + n2));
        NSLog(@"SUBTRACTION = %d", (n1 - n2));
        NSLog(@"MULTIPLICATION = %d", (n1 * n2));
        NSLog(@"DIVISION = %d", (n1 / n2));
        NSLog(@"MODULUS = %d", (n1 % n2));
    
        [pool drain];
        return 0;
    }

    Output:

    ADDITION = 8
    SUBTRACTION = 2
    MULTIPLICATION = 15
    DIVISION = 1
    MODULUS = 2

    3. Relational (Comparison) Operators: Relational operators compare two values, returning true or false based on the comparison.

    OperatorDescriptionExample
    ==Checks if two operands are equal(a == b) // false
    !=Checks if two operands are not equal(a != b) // true
    >Checks if left operand is greater(a > b) // true
    <Checks if left operand is smaller(a < b) // false
    >=Checks if left operand is greater or equal(a >= b) // true
    <=Checks if left operand is smaller or equal(a <= b) // false

    Examples:

    #import <Foundation/Foundation.h>
    
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        int n1 = 5, n2 = 3;
        NSLog(@"Equal = %d", (n1 == n2));
        NSLog(@"NOT Equal = %d", (n1 != n2));
        NSLog(@"LESS THAN = %d", (n1 < n2));
        NSLog(@"GREATER THAN = %d", (n1 > n2));
    
        [pool drain];
        return 0;
    }

    Output:

    Equal = 0
    NOT Equal = 1
    LESS THAN = 0
    GREATER THAN = 1

    4. Logical Operators: Logical operators perform logical operations and return either true (1) or false (0).

    OperatorDescriptionExample
    &&Called Logical AND operator. If both the operands are non zero then condition becomes true.(A && B) is false.
    ||Called Logical OR Operator. If any of the two operands is non zero then condition becomes true.(A || B) is true.
    !Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false.!(A && B) is true.

    Example:

    #import <Foundation/Foundation.h>
    
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        int n1 = 1, n2 = 0;
        NSLog(@"LOGICAL AND = %d", (n1 && n2));
        NSLog(@"LOGICAL OR = %d", (n1 || n2));
        NSLog(@"LOGICAL NOT = %d", (!n1));
    
        [pool drain];
        return 0;
    }

    Output:

    LOGICAL AND = 0
    LOGICAL OR = 1
    LOGICAL NOT = 0

    5. Bitwise Operators: Bitwise operators operate on bits and are often used for low-level programming.

    pqp & qp | qp ^ q
    00000
    01011
    11110
    10011

    Example:

    #import <Foundation/Foundation.h>
    
    int main (int argc, const char * argv[])
    {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        // n1 = 12(00001100), n2 = 10(00001010)
        int n1 = 12, n2 = 10;
    
        // The result is 00001000
        NSLog(@"Bitwise AND(n1&n2) = %d\n", (n1 & n2));
    
        // The result is 00001110
        NSLog(@"Bitwise OR(n1|n2) = %d\n", (n1 | n2));
    
        // The result is 00101000
        NSLog(@"LEFT SHIFT(n2<<2) = %d\n", (n2 << 2));
    
        // The result is 00000010
        NSLog(@"RIGHT SHIFT(n2>>2) = %d\n", (n2 >> 2));
    
        // The result is 00000110
        NSLog(@"XOR(n1^n2) = %d\n", (n1 ^ n2));
    
        // The result is 11110011
        NSLog(@"ONCE COMPLIMENT(~n1) = %d\n", (~n1));
    
        [pool drain];
        return 0;
    }
    • Bitwise AND:
      n1&n2=12&10n1 \& n2 = 12 \& 10n1&n2=12&10
      Binary: 00001100&00001010=0000100000001100 \& 00001010 = 0000100000001100&00001010=00001000
      Result: 8
    • Bitwise OR:
      n1∣n2=12∣10n1 | n2 = 12 | 10n1∣n2=12∣10
      Binary: 00001100∣00001010=0000111000001100 | 00001010 = 0000111000001100∣00001010=00001110
      Result: 14
    • Left Shift (<<):
      n2<<2=10<<2n2 << 2 = 10 << 2n2<<2=10<<2
      Binary: 00001010<<2=0010100000001010 << 2 = 0010100000001010<<2=00101000
      Result: 40
    • Right Shift (>>):
      n2>>2=10>>2n2 >> 2 = 10 >> 2n2>>2=10>>2
      Binary: 00001010>>2=0000001000001010 >> 2 = 0000001000001010>>2=00000010
      Result: 2
    • XOR:
      n1⊕n2=12⊕10n1 \oplus n2 = 12 \oplus 10n1⊕n2=12⊕10
      Binary: 00001100⊕00001010=0000011000001100 \oplus 00001010 = 0000011000001100⊕00001010=00000110
      Result: 6
    • One’s Complement (~):
      ∼n1=∼12\sim n1 = \sim 12∼n1=∼12
      Binary: ∼00001100=11110011\sim 00001100 = 11110011∼00001100=11110011 (in two’s complement, signed integer representation)
      Result: -13

    6. Assignment Operators: Assignment operators assign values or results of expressions to variables.

    OperatorDescription
    =Assign value
    +=Add and assign
    -=Subtract and assign
    *=Multiply and assign
    /=Divide and assign
    %=Modulus and assign
    <<=Left shift and assign
    >>=Right shift and assign
    &=Bitwise AND and assign
    ^=Bitwise XOR and assign

    Example:

    #import <Foundation/Foundation.h>
    
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        int n1 = 20;
        n1 += 10;
        NSLog(@"After +=: %d", n1);
        n1 &= 2;
        NSLog(@"After &=: %d", n1);
    
        [pool drain];
        return 0;
    }

    Output:

    After +=: 30
    After &=: 2
    Miscellaneous or Special Operators

    Special operators are unique to programming languages and are used to perform specific tasks.

    OperatorDescriptionExample
    sizeof()Returns the size of a variable in bytes.int a = 10; sizeof(a); // Returns 4 bytes
    &Returns the address of a variable.&a; // Returns the address of 'a'
    *Used to create a pointer variable.int a = 10; int *b = &a; // Pointer to 'a'
    ?:Conditional (ternary) operator, an alternative to if-else.int number1 = 5, number2 = 10, max; max = (number1 > number2) ? number1 : number2; // max = 10

    Example:

    Size of num1 (int) = 4 bytes
    Value of num1 = 8
    Value pointed by ptr = 8
    Result (a == 10) = 0
    Result (a == 15) = 1
    Operator Precedence

    Operator precedence determines the order in which operators are evaluated in an expression based on their priority. If two or more operators have the same precedence, their associativity determines the evaluation order. Associativity can be either left-to-right or right-to-left.

    For example:
    In the expression m = 5 - 2 / 2, the result is m = 4, not m = 1, because / (division) has higher precedence than - (subtraction). First, 2 / 2 is evaluated, then 5 - 1.

    Operator Precedence Table

    OperatorAssociativity
    () [] -> . ++ --Left-to-right
    + - ! ~ ++ -- (type) * & sizeof()Right-to-left
    * / %Left-to-right
    << >>Left-to-right
    == !=Left-to-right
    ^ | Left to right
    && `Left to right
    ?:Right-to-left
    = += -= *= /= %= >>= <<= &= ^= `Right to left 
    , (comma)Left-to-right
  • Variables and Data Types

    Data Types in Objective-C

    In Objective-C, each variable is associated with a data type, and each data type requires a specific amount of memory in the system. A data type defines the kind of data a variable will store and the space it occupies in memory. Data types in Objective-C are classified as follows:

    TypeDescription
    Primitive Data TypesArithmetic types, further classified into integer and floating-point data types.
    Void TypesData types with no value or operator, used when functions do not return a value.
    Derived TypesIncludes pointers, arrays, structures, unions, and function types.
    Enumerated TypesArithmetic types used to define variables restricted to certain discrete integer values.
    Data Types and Their Properties

    Below is the list of common data types in Objective-C along with their storage sizes, format specifiers, and example constants:

    TypeStorage SizeFormat SpecifierExamples
    char1 byte%c'a''\n'
    short int2 bytes%hi%hx%ho
    unsigned short int2 bytes%hu%hx%ho
    int2 or 4 bytes%i%x%o12-970xFFE0
    unsigned int2 or 4 bytes%u%x%o12u100U
    long int8 bytes%li%lx%lo12L-2001
    unsigned long int8 bytes%lu%lx%lo12UL0xffeeUL
    long long int8 bytes%lli%llx%llo0xe5e5e5e5LL
    unsigned long long int8 bytes%llu%llx%llo12ull0xffeeULL
    float4 bytes%f%e%g%a12.34f3.1e-5f
    double8 bytes%f%e%g%a12.343.1e-5
    long double10 bytes%Lf%Le%Lg12.34L3.1e-5l
    Primitive Data Types Examples

    1. Integers: The int type is used to store whole numbers, including decimal, hexadecimal, and octal values. Unsigned integers store only positive values.

    Example:

    #import <Foundation/Foundation.h>
    int main() {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        int a = 9;         // Positive integer
        int b = -9;        // Negative integer
        unsigned int c = 89U;  // Unsigned integer
        long int d = 9998L;    // Long integer
    
        NSLog(@"Positive Integer: %i", a);
        NSLog(@"Negative Integer: %d", b);
        NSLog(@"Unsigned Integer: %u", c);
        NSLog(@"Long Integer: %li", d);
    
        [pool drain];
        return 0;
    }

    Output:

    Positive Integer: 9
    Negative Integer: -9
    Unsigned Integer: 89
    Long Integer: 9998

    2. Short Integers: The short int type is used for storing 2-byte integer values, which can be positive or negative.

    Example:

    #import <Foundation/Foundation.h>
    int main() {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        short int number = 67;
        NSLog(@"Short Integer Value: %hi", number);
    
        [pool drain];
        return 0;
    }

    Output:

    Short Integer Value: 67

    3. Long Integers: The long int type is used when standard int is insufficient for large values.

    Example:

    #import <Foundation/Foundation.h>
    int main() {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        long int bigInt = 9223372036854775807;
        NSLog(@"Long Integer Value: %li", bigInt);
    
        [pool drain];
        return 0;
    }

    Output:

    Long Integer Value: 9223372036854775807

    4. Character Data Type: Stores single characters, typically 1 byte.

    Example:

    #import <Foundation/Foundation.h>
    int main() {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        char a = 'a';
        NSLog(@"Character Value: %c", a);
    
        a++;
        NSLog(@"After Increment: %c", a);
    
        [pool drain];
        return 0;
    }

    Output:

    Character Value: a
    After Increment: b

    5. Floating Point Types: Floating-point types store decimal numbers.

    Example:

    #import <Foundation/Foundation.h>
    int main() {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        float a = 9.8f;
        float b = 2.5f;
    
        NSLog(@"Float A: %f", a);
        NSLog(@"Float B: %f", b);
    
        [pool drain];
        return 0;
    }

    Output:

    Float A: 9.800000
    Float B: 2.500000

    6. Double Types: Double precision floating-point values.

    Example:

    #import <Foundation/Foundation.h>
    int main() {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        double a = 12345.678;
        NSLog(@"Double Value: %lf", a);
    
        [pool drain];
        return 0;
    }

    Output:

    Double Value: 12345.678000

    7. Boolean Type: Used to store true or false values, represented as YES or NO.

    Example:

    #import <Foundation/Foundation.h>
    int main() {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        BOOL isStudent = YES;
    
        if (isStudent) {
            NSLog(@"The person is a student.");
        } else {
            NSLog(@"The person is not a student.");
        }
    
        [pool drain];
        return 0;
    }

    Output:

    The person is a student.

    8. String Data Type: Strings are objects created using the NSString class.

    Example:

    #import <Foundation/Foundation.h>
    int main() {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        NSString *name = @"Objective-C";
        NSLog(@"Programming Language: %@", name);
    
        [pool drain];
        return 0;
    }

    Output:

    Programming Language: Objective-C

    Variables in Objective-C

    A variable is a name given to a storage area that programs can manipulate. Each variable in Objective-C has a specific type that determines the size and layout of the variable’s memory, the range of values that can be stored, and the operations that can be applied.

    The name of a variable can be composed of letters, digits, and underscores. It must begin with a letter or an underscore. Uppercase and lowercase letters are distinct because Objective-C is case-sensitive. The following are the basic variable types in Objective-C:

    Sr. No.TypeDescription
    1charTypically a single octet (one byte). This is an integer type.
    2intThe most natural size of integer for the machine.
    3floatA single-precision floating-point value.
    4doubleA double-precision floating-point value.
    5voidRepresents the absence of type.

    Objective-C also allows various other types of variables, such as enumerations, pointers, arrays, structures, and unions, which are covered in later chapters. This section focuses on basic variable types.

    Variable Definition in Objective-C

    A variable definition tells the compiler where and how much storage to allocate for the variable. A definition specifies the data type and a list of one or more variables of that type as follows:

    type variable_list;

    Here, type must be a valid Objective-C data type, such as charintfloatdoubleBOOL, or any user-defined object, and variable_list may consist of one or more identifier names separated by commas. Examples include:

    int i, j, k;
    char c, ch;
    float f, salary;
    double d;

    Variables can be initialized during their declaration using the following syntax:

    type variable_list;

    Here, type must be a valid Objective-C data type, such as charintfloatdoubleBOOL, or any user-defined object, and variable_list may consist of one or more identifier names separated by commas. Examples include:

    int i, j, k;
    char c, ch;
    float f, salary;
    double d;

    Variables can be initialized during their declaration using the following syntax:

    type variable_name = value;

    Examples:

    int a = 3, b = 5;      // Definition and initialization
    char x = 'x';          // The variable x has the value 'x'
    float pi = 3.14;       // Definition and initialization

    For variables without an initializer:

    • Variables with static storage duration are initialized to NULL (all bytes have the value 0).
    • The initial value of all other variables is undefined.
    Variable Declaration in Objective-C

    A variable declaration informs the compiler of a variable’s type and name, enabling the compiler to proceed with compilation without requiring the variable’s complete details. Declarations are particularly useful when working with multiple files. For instance, you can declare a variable in one file and define it in another using the extern keyword.

    extern int a, b;
    extern float pi;

    Though a variable can be declared multiple times, it can be defined only once in a file, function, or block of code.

    Examples:

    #import <Foundation/Foundation.h>
    
    // Variable declaration
    extern int a, b;
    extern int c;
    extern float f;
    
    int main () {
      /* Variable definition */
      int a, b;
      int c;
      float f;
    
      /* Variable initialization */
      a = 10;
      b = 20;
    
      c = a + b;
      NSLog(@"Value of c: %d", c);
    
      f = 70.0 / 3.0;
      NSLog(@"Value of f: %f", f);
    
      return 0;
    }

    Output:

    Value of c: 30
    Value of f: 23.333334
    Lvalues and Rvalues in Objective-C

    Expressions in Objective-C can be categorized as:

    • Lvalue: Refers to a memory location and can appear on the left or right side of an assignment.
    • Rvalue: Refers to a data value stored at an address and can appear only on the right side of an assignment.

    Example of Valid assignment:

    int g = 20;

    Example of  Invalid assignment:

    10 = 20; // Compile-time error
  • Overview of Objective-C

    Introduction to Objective-C

    Objective-C is an object-oriented programming language that extends the C language with additional features, primarily for use in macOS and iOS applications. It was originally developed in the early 1980s by Brad Cox and Tom Love and later became the primary programming language used by Apple for its software development.

    Uses of Objective-C

    1. iOS and macOS App Development: Objective-C has been the cornerstone for developing applications on Apple platforms, ranging from mobile and desktop applications to utilities and games.
    2. Legacy Codebases: Many existing iOS and macOS projects are built using Objective-C. Developers with expertise in Objective-C are often needed to maintain, extend, or modernize these projects.
    3. Cocoa and Cocoa Touch Frameworks: These frameworks are integral to macOS and iOS development. Objective-C seamlessly integrates with these frameworks, enabling developers to create user interfaces, handle events, and access system services.
    4. Open Source Projects: Objective-C is commonly used in open-source libraries and tools. For example, GNUStep offers a cross-platform implementation of the Cocoa API for Objective-C development.
    5. High-Level Abstractions: Its object-oriented features allow developers to create modular and reusable software components using classes, objects, inheritance, and polymorphism.

     Comparison: Objective-C vs. Swift

    CriteriaObjective-CSwift
    SyntaxSyntax is verbose and uses square brackets for method calls, which can be unfamiliar.Syntax is concise and modern, utilizing dot notation for method calls, similar to other languages.
    ReadabilityRequires manual handling of pointers and memory, making code complex.Offers features like optionals and type inference, enhancing readability and reducing boilerplate.
    PerformanceReliable due to years of optimization but dynamic typing can impact performance.Designed for speed and efficiency with modern compilers, outperforming Objective-C in many cases.
    SafetyRelies on manual memory management and lacks compile-time nullability checks.Prioritizes safety with features like optionals, strong typing, and compile-time checks.
    InteroperabilityEasily integrates with Swift via bridging headers, allowing incremental migration.Can call Objective-C APIs directly, ensuring seamless interaction between the two languages.
    Learning CurveSteep due to complex syntax and manual memory management.Easier for developers familiar with modern languages, offering a beginner-friendly experience.
    CommunityLarge existing codebase but declining adoption in favor of Swift.Rapidly growing community with strong Apple support and open-source adoption beyond Apple platforms.

    Characteristics of Objective-C

    1. Object-Oriented: Objective-C is built on top of C, adding object-oriented capabilities, which allow developers to define classes and objects, promoting code reusability and modularity.
    2. Dynamic Typing: Objective-C supports dynamic typing, which means that the type of an object is determined at runtime, allowing for more flexible and adaptable code.
    3. Message Passing: Unlike function calls in C, Objective-C uses a messaging model similar to Smalltalk. Messages are sent to objects, and the method invoked is determined at runtime, enabling polymorphism and dynamic behavior.
    4. Categories and Protocols: Categories allow you to add methods to existing classes without modifying the original class. Protocols define a set of methods that a class can implement, similar to interfaces in other languages, facilitating polymorphic behavior.
    5. Interoperability with C and C++: Objective-C is fully compatible with C, allowing developers to include C code and libraries directly. It can also work with C++ code using Objective-C++.
    6. Automatic Reference Counting (ARC): ARC is a memory management feature that automatically handles the retain and release of objects, reducing the need for manual memory management and minimizing memory leaks.
    7. Rich Foundation Framework: Objective-C includes a powerful Foundation framework that provides essential classes and APIs for data management, collections, string manipulation, and more, forming the core of macOS and iOS development.
    8. Cocoa and Cocoa Touch Frameworks: These frameworks provide a comprehensive set of APIs for building macOS and iOS applications, including user interface components, networking, graphics, and data persistence.
    9. Backward Compatibility: Objective-C maintains backward compatibility with older versions of the language, allowing developers to continue using legacy code while taking advantage of new features.
    10. Bridging with Swift: Objective-C is interoperable with Swift, Apple’s modern programming language, allowing developers to gradually integrate Swift into existing Objective-C codebases.

    Limitations of Objective-C

    1. Verbose Syntax: Objective-C’s syntax, with features like square brackets for method calls, can be challenging for developers accustomed to modern languages.
    2. Declining Trend: With Swift’s emergence, the industry is shifting towards newer, more efficient languages, impacting the demand for Objective-C.
    3. Manual Memory Management: Developers must handle memory manually, increasing the risk of errors like memory leaks and crashes.
    4. Limited Safety Features: Objective-C lacks many safety features found in Swift, such as compile-time nullability checks, leading to potential runtime errors.
    5. Steep Learning Curve: New developers may find Objective-C difficult to learn due to its syntax and manual memory management requirements.
    6. Transition to Swift: While Objective-C and Swift are interoperable, migrating projects or integrating codebases can be complex and time-consuming.

    Examples and Outputs

    #import <Foundation/Foundation.h>
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            // Basic program to print a message
            NSLog(@"Hello from Objective-C!");
        }
        return 0;
    }

    Output:

    Hello from Objective-C!
  • Objective-C Tutorial Roadmap

    Introduction to Objective-C

    What is Objective-C?

    Objective-C is an object-oriented programming language that extends the C language with messaging and runtime features, widely used for macOS and iOS development before Swift.

    Characteristics of Objective-C

    • Object-oriented and dynamic
    • Superset of the C programming language
    • Message-passing syntax
    • Powerful runtime system
    • Seamless integration with C and C++

    Variables and Data Types in Objective-C

    Data Types in Objective-C

    • Primitive data types
    • Derived data types
    • User-defined data types

    Variables

    • Variable declaration and initialization
    • Scope and lifetime of variables

    Operators in Objective-C

    Types of Operators

    • Arithmetic operators
    • Relational operators
    • Logical operators
    • Assignment operators
    • Bitwise operators

    Loops in Objective-C

    Types of Loops

    • for loop
    • while loop
    • do-while loop
    • Nested loops

    Functions in Objective-C

    Defining and Calling Functions

    • Function syntax
    • Function declarations and definitions

    Parameters and Return Values

    • Passing arguments to functions
    • Returning values

    Function Pointers

    • Understanding function pointers
    • Use cases and examples

    Blocks in Objective-C

    Introduction to Blocks

    • What are blocks?
    • Syntax of blocks

    Types of Blocks

    • Global blocks
    • Stack blocks
    • Heap blocks

    Numbers in Objective-C

    Number Types

    • Integer types
    • Floating-point numbers
    • NSNumber class

    Arrays in Objective-C

    Working with Arrays

    • Creating arrays
    • Accessing and modifying array elements

    Object-Oriented Programming in Objective-C

    Classes and Objects

    • Syntax and keywords
    • Types of classes
    • Types of objects

    Creating Subclasses

    • Inheritance basics

    Method Overriding

    • Overriding parent class methods
    • Using super to access parent methods

    Dynamic Typing and Polymorphism

    • Dynamic method resolution
    • Runtime polymorphism

    Pointers in Objective-C

    Pointer Basics

    • Understanding pointers
    • NULL pointers

    Pointer Operations

    • Pointer arithmetic
    • Array of pointers
    • Pointer to pointer

    Pointers and Functions

    • Passing pointers to functions
    • Returning pointers from functions

    Strings in Objective-C

    String Types

    • C-style strings
    • NSString and NSMutableString

    Structures in Objective-C

    Structures

    • Defining and using structures

    Pointers to Structures

    • Accessing structure members using pointers

    Preprocessors in Objective-C

    Preprocessors

    • Macro definitions
    • File inclusion

    Types of Preprocessors

    • #define
    • #include
    • Conditional compilation

    Typedef in Objective-C

    Typedef Usage

    • Creating aliases using typedef

    Typedef vs #define

    • Key differences and use cases

    Type Casting in Objective-C

    Type Casting

    • Implicit type casting
    • Explicit type casting

    Error, Log, and File Handling in Objective-C

    Log Handling

    • Using NSLog
    • Debugging techniques

    File Handling

    • Reading from files
    • Writing to files

    Error Handling

    • NSError and exception handling

    Command Line Arguments in Objective-C

    Command Line Arguments

    • Accessing arguments in Objective-C programs
    • Practical examples

    Inheritance in Objective-C

    Types of Inheritance

    • Single inheritance
    • Multilevel inheritance

    Data Encapsulation in Objective-C

    Encapsulation Concepts

    • Access specifiers
    • Data hiding and abstraction

    Categories in Objective-C

    Introduction to Categories

    • Extending existing classes

    Category Usage

    • Adding methods without subclassing

    Posing in Objective-C

    Posing

    • Understanding posing
    • Types of posing

    Extensions in Objective-C

    Class Extensions

    • Private methods and properties
    • Difference between categories and extensions

    Dynamic Binding in Objective-C

    Dynamic Binding

    • Runtime method binding

    Use Cases

    • Flexibility and dynamic behavior

    Composite Objects in Objective-C

    Composite Objects

    • Object composition

    Types of Composite Objects

    • Aggregation
    • Composition

    Foundation Framework in Objective-C

    Introduction to Foundation Framework

    • Core classes and utilities

    Types and Subtypes

    • Collections
    • Strings
    • Dates
    • File management

    Fast Enumeration in Objective-C

    Fast Enumeration

    • Iterating collections efficiently

    Memory Management in Objective-C

    Memory Management Concepts

    • Reference counting
    • ARC (Automatic Reference Counting)

    Best Practices

    • Avoiding memory leaks
    • Managing object lifecycles

  • DOM Function

    DOMAttr

    __construct()
    Description: Constructs a new DOMAttr object. This is used to create an attribute node with a specified name and value.
    Example:

    $doc = new DOMDocument();
    $attr = new DOMAttr("id", "unique-value");
    echo $attr->name;  // Output: id
    echo $attr->value; // Output: unique-value

    isId()
    Description: Checks if this attribute is an ID attribute.
    Example:

    $doc = new DOMDocument();
    $element = $doc->createElement("example");
    $attr = $doc->createAttribute("id");
    $attr->value = "unique-id";
    $element->setAttributeNode($attr);
    echo $attr->isId() ? "true" : "false";
    // Output: true (if the attribute is declared as an ID in a DTD)

    DOMCdataSection

    __construct()
    Description: Constructs a new DOMCdataSection object. This is used to create a CDATA section within the document.
    Example:

    $doc = new DOMDocument();
    $cdata = $doc->createCDATASection("This is a CDATA section.");
    $doc->appendChild($cdata);
    echo $doc->saveXML();
    // Output: <!DOCTYPE example><![CDATA[This is a CDATA section.]]&gt;

    DOMDocument

    __construct()
    Description: Constructs a new DOMAttr object. This is used to create an attribute node with a specified name and value.
    Example:

    $doc = new DOMDocument();
    $attr = new DOMAttr("id", "unique-value");
    echo $attr->name;  // Output: id
    echo $attr->value; // Output: unique-value

    createAttribute()
    Description: Creates a new attribute node with the specified name.
    Example:

    $doc = new DOMDocument();
    $element = $doc->createElement("example");
    $attr = $doc->createAttribute("id");
    $attr->value = "unique-id";
    $element->setAttributeNode($attr);
    echo $attr->isId() ? "true" : "false";
    // Output: true (if the attribute is declared as an ID in a DTD)

    count()
    Description: Get the count of elements present in a PriorityQueue instance.
    Example:

    $doc = new DOMDocument();
    $attr = $doc->createAttribute("class");
    $attr->value = "my-class";
    echo $attr->name;  // Output: class

    createAttributeNS()
    Description: Creates a new attribute with the specified namespace URI and qualified name.
    Example:

    $doc = new DOMDocument();
    $attr = $doc->createAttributeNS("http://example.com", "ex:attr");
    $attr->value = "value";
    echo $attr->name;  // Output: ex:attr

    createCDATASection()
    Description: Creates a new CDATA section.
    Example:

    $doc = new DOMDocument();
    $cdata = $doc->createCDATASection("CDATA Content");
    $doc->appendChild($cdata);
    echo $doc->saveXML();
    // Output: <!DOCTYPE example><![CDATA[CDATA Content]]&gt;

    createComment()
    Description: Creates a new comment node.
    Example:

    $doc = new DOMDocument();
    $comment = $doc->createComment("This is a comment.");
    $doc->appendChild($comment);
    echo $doc->saveXML();
    // Output: <!--This is a comment.-->

    createDocumentFragment()
    Description: Creates an empty DOMDocumentFragment object.
    Example:

    $doc = new DOMDocument();
    $fragment = $doc->createDocumentFragment();
    $fragment->appendXML("<example>Content</example>");
    $doc->appendChild($fragment);
    echo $doc->saveXML();
    // Output: <example>Content</example>

    createElement()
    Description: Creates a new element with the given tag name.
    Example:

    $doc = new DOMDocument();
    $element = $doc->createElement("example", "This is content.");
    $doc->appendChild($element);
    echo $doc->saveXML();
    // Output: <example>This is content.</example>

    createElementNS()
    Description: Creates a new element with a namespace URI and qualified name.
    Example:

    $doc = new DOMDocument();
    $element = $doc->createElementNS("http://example.com", "ex:example", "Content");
    $doc->appendChild($element);
    echo $doc->saveXML();
    // Output: <ex:example xmlns:ex="http://example.com">Content</ex:example>

    createEntityReference()
    Description: Creates a new entity reference.
    Example:

    $doc = new DOMDocument();
    $entity = $doc->createEntityReference("copy");
    $doc->appendChild($entity);
    echo $doc->saveXML();
    // Output: &copy;

    createProcessingInstruction()
    Description: Creates a new processing instruction.
    Example:

    $doc = new DOMDocument();
    $pi = $doc->createProcessingInstruction("php", "echo 'Hello';");
    $doc->appendChild($pi);
    echo $doc->saveXML();
    // Output: <?php echo 'Hello';?>

    createTextNode()
    Description: Creates a new text node.
    Example:

    $doc = new DOMDocument();
    $text = $doc->createTextNode("This is text.");
    $doc->appendChild($text);
    echo $doc->saveXML();
    // Output: This is text.

    getElementById()
    Description: Returns an element by its ID.
    Example:

    $doc = new DOMDocument();
    $doc->loadXML('<example id="unique">Content</example>');
    echo $doc->getElementById("unique")->nodeValue;
    // Output: Content

    getElementsByTagName()
    Description: Returns a list of elements by tag name.
    Example:

    $doc = new DOMDocument();
    $doc->loadXML("<root><child>One</child><child>Two</child></root>");
    $elements = $doc->getElementsByTagName("child");
    foreach ($elements as $element) {
        echo $element->nodeValue . "\n";
    }
    // Output: One Two

    getElementsByTagNameNS()
    Description: Returns a list of elements by tag name within a namespace.
    Example:

    $doc = new DOMDocument();
    $doc->loadXML('<root xmlns:ex="http://example.com"><ex:child>Content</ex:child></root>');
    $elements = $doc->getElementsByTagNameNS("http://example.com", "child");
    foreach ($elements as $element) {
        echo $element->nodeValue . "\n";
    }
    // Output: Content

    importNode()
    Description: Imports a node from another document.
    Example: 

    $doc1 = new DOMDocument();
    $doc1->loadXML("<example>Content</example>");
    $doc2 = new DOMDocument();
    $imported = $doc2->importNode($doc1->documentElement, true);
    $doc2->appendChild($imported);
    echo $doc2->saveXML();
    // Output: <example>Content</example>

    load()
    Description: Loads an XML document from a file.
    Example:

    $doc = new DOMDocument();
    $doc->load("file.xml");
    echo $doc->saveXML();

    DOMDocumentFragment

    DOMDocumentFragment appendXML() Function
    Description: Find and return an element in the PriorityQueue by a condition.
    Example:

    $doc = new DOMDocument();
    $fragment = $doc->createDocumentFragment();
    
    $xml = "<item>First Item</item><item>Second Item</item>";
    $fragment->appendXML($xml);
    
    $root = $doc->createElement("root");
    $doc->appendChild($root);
    $root->appendChild($fragment);
    
    echo $doc->saveXML();
    // Output:
    // <root><item>First Item</item><item>Second Item</item></root>

    __construct()
    Description: Initializes a new DOMElement object.
    Example:

    $dom = new DOMDocument();
    $element = $dom->createElement("example", "Hello World");
    echo $element->nodeName;
    // Output: example

    DOMElement

    __construct()

    Description: Initializes a new DOMElement object.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $reversed = array_reverse($pq->toArray());
    
    print_r($reversed);
    // Output: Array ( [0] => One [1] => Two [2] => Three )

    getAttribute()
    Description: Retrieves the value of an attribute by name.
    Example:

    $doc = new DOMDocument();
    $element = $doc->createElement('example');
    $element->setAttribute('id', '123');
    echo $element->getAttribute('id');
    // Output: 123

    getAttributeNode()
    Description: Retrieves the attribute node by name.
    Example:

    $doc = new DOMDocument();
    $element = $doc->createElement('example');
    $element->setAttribute('id', '123');
    $attrNode = $element->getAttributeNode('id');
    echo $attrNode->name . ' = ' . $attrNode->value;
    // Output: id = 123

    getAttributeNodeNS()
    Description: Retrieves an attribute node by its namespace URI and name.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Another One", 1);
    
    $priorityToExtract = 1;
    $extracted = array_filter($pq->toArray(), function ($item) use ($priorityToExtract) {
        return $item[1] === $priorityToExtract;
    });
    
    print_r($extracted);
    // Output: Array ( [0] => One [1] => Another One )

    getAttributeNS()
    Description: Retrieves the value of an attribute by namespace URI and name.
    Example:

    $doc = new DOMDocument();
    $element = $doc->createElement('example');
    $element->setAttributeNS('http://example.com/ns', 'ex:id', '789');
    echo $element->getAttributeNS('http://example.com/ns', 'id');
    // Output: 789

    DOMEntityReference

    __construct()
    Description: Initializes a new DOMEntityReference object, which represents an entity reference in the DOM. Entity references are placeholders for entities that are replaced by their defined content in the XML or HTML document.

    Example:

    $doc = new DOMDocument();
    $entityRef = $doc->createEntityReference('copy');
    $doc->appendChild($entityRef);
    echo $doc->saveXML();
    // Output: &copy;

    DOMImplementation

    __construct()

    Description: Initializes a new DOMImplementation object, which provides methods for operations independent of the document instance.

    Example:

    $domImpl = new DOMImplementation();
    var_dump($domImpl instanceof DOMImplementation);
    // Output: bool(true)

    createDocument()
    Description: Creates a new DOMDocument object with an optional namespace URI, qualified name, and document type.
    Example:

    $domImpl = new DOMImplementation();
    $doc = $domImpl->createDocument("http://www.example.com", "example:root");
    echo $doc->saveXML();
    // Output: <?xml version="1.0"?><example:root xmlns:example="http://www.example.com"/>

    createDocumentType()
    Description: Creates a new DOMDocumentType object. It is used to define the document type declaration.
    Example:

    $domImpl = new DOMImplementation();
    $doctype = $domImpl->createDocumentType("html", "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");
    echo $doctype->name; // Output: html

    hasFeature()
    Description: Checks if the DOMImplementation object supports a specific feature and version.
    Example:

    $doc = new DOMDocument();
    $attr = $doc->createAttribute('id');
    $attr->value = '456';
    $element = $doc->createElement('example');
    $element->setAttributeNode($attr);
    echo $element->getAttribute('id');
    // Output: 456

    setAttributeNodeNS()
    Description: Adds a new attribute node with a namespace to the element.
    Example:

    $domImpl = new DOMImplementation();
    if ($domImpl->hasFeature("XML", "1.0")) {
        echo "Feature XML 1.0 is supported.";
    } else {
        echo "Feature not supported.";
    }
    // Output: Feature XML 1.0 is supported.

    DOMNamedNodeMap

    count()
    Description: Returns the number of items in the DOMNamedNodeMap.
    Example:

    $dom = new DOMDocument();
    $dom->loadXML('<root attr1="value1" attr2="value2" attr3="value3"/>');
    $attributes = $dom->documentElement->attributes;
    echo $attributes->count();
    // Output: 3

    getNamedItem()
    Description: Retrieves a node specified by name from the DOMNamedNodeMap.
    Example:

    $dom = new DOMDocument();
    $dom->loadXML('<root attr1="value1" attr2="value2"/>');
    $attributes = $dom->documentElement->attributes;
    $attr = $attributes->getNamedItem('attr1');
    echo $attr->nodeValue;
    // Output: value1

    item()
    Description: Returns a node at the specified index in the DOMNamedNodeMap.
    Example:

    $dom = new DOMDocument();
    $dom->loadXML('<root attr1="value1" attr2="value2"/>');
    $attributes = $dom->documentElement->attributes;
    $attr = $attributes->item(0);
    echo $attr->nodeName . ": " . $attr->nodeValue;
    // Output: attr1: value1

    DOMNode

    appendChild()
    Description: Appends a new child node to the DOM node. This function adds the node to the list of children of the current node.
    Example:

    $doc = new DOMDocument();
    $element = $doc->createElement('example');
    $element->setAttributeNS('http://example.com/ns', 'ex:id', 'unique');
    $element->setIdAttributeNS('http://example.com/ns', 'id', true);
    echo $doc->getElementById('unique')->nodeName;
    // Output: example

    C14N()
    Description: Canonicalizes the XML of the current node and returns it as a string.
    Example:

    $dom = new DOMDocument();
    $element = $dom->createElement("example", "Hello World!");
    $dom->appendChild($element);
    $element->C14NFile("example.xml");
    // The file "example.xml" will contain the canonicalized XML.

    cloneNode()
    Description: Creates a duplicate of the current node. It can clone the node with or without its children.
    Example:

    $dom = new DOMDocument();
    $element = $dom->createElement("example", "Clone me!");
    $dom->appendChild($element);
    $clone = $element->cloneNode(true);
    $dom->appendChild($clone);
    echo $dom->saveXML();
    // Output: <example>Clone me!</example><example>Clone me!</example>

    getLineNo()
    Description: Returns the line number of the current node within the document.
    Example:

    $dom = new DOMDocument();
    $dom->loadXML('<root><child>Content</child></root>');
    $child = $dom->getElementsByTagName("child")->item(0);
    echo $child->getLineNo();
    // Output: 2 (This depends on the line where the <child> element is located)

    getNodePath()
    Description: Returns the XPath of the node.
    Example:

    $dom = new DOMDocument();
    $dom->loadXML('<root><parent><child>Value</child></parent></root>');
    $child = $dom->getElementsByTagName("child")->item(0);
    echo $child->getNodePath();
    // Output: /root/parent/child

    hasAttributes()
    Description: Checks if the current node has attributes.
    Example:

    $dom = new DOMDocument();
    $element = $dom->createElement("example");
    $element->setAttribute("attr", "value");
    echo $element->hasAttributes() ? "Has attributes" : "No attributes";
    // Output: Has attributes

    hasChildNodes()
    Description: Checks if the current node has child nodes.
    Example:

    $dom = new DOMDocument();
    $parent = $dom->createElement("parent");
    $child = $dom->createElement("child");
    $parent->appendChild($child);
    echo $parent->hasChildNodes() ? "Has child nodes" : "No child nodes";
    // Output: Has child nodes

    insertBefore()
    Description: Inserts a new node before a specified reference node.
    Example:

    $dom = new DOMDocument();
    $parent = $dom->createElement("parent");
    $child1 = $dom->createElement("child1");
    $child2 = $dom->createElement("child2");
    $parent->appendChild($child1);
    $parent->insertBefore($child2, $child1);
    echo $dom->saveXML();
    // Output: <parent><child2/><child1/></parent>

    isDefaultNamespace()
    Description: Checks if the given namespace URI is the default namespace for the current node.
    Example:

    $dom = new DOMDocument();
    $element = $dom->createElementNS("http://www.example.com", "example:element");
    echo $element->isDefaultNamespace("http://www.example.com") ? "Default namespace" : "Not default namespace";
    // Output: Default namespace

    isSameNode()
    Description: Checks if two nodes are the same node.
    Example:

    $dom = new DOMDocument();
    $element = $dom->createElement("example");
    $clone = $element->cloneNode();
    echo $element->isSameNode($clone) ? "Same node" : "Different nodes";
    // Output: Different nodes

    isSupported()
    Description: Checks if the current node supports the specified feature and version.
    Example:

    $dom = new DOMDocument();
    $element = $dom->createElement("example");
    echo $element->isSupported("core", "1.0") ? "Supported" : "Not supported";
    // Output: Supported

    lookupNamespaceUri()
    Description: Looks up the URI associated with a namespace prefix.
    Example:

    $dom = new DOMDocument();
    $element = $dom->createElementNS("http://www.example.com", "example:element");
    echo $element->lookupNamespaceUri("example");
    // Output: http://www.example.com

    lookupPrefix()
    Description: Looks up the prefix associated with a given namespace URI.
    Example:

    $dom = new DOMDocument();
    $element = $dom->createElementNS("http://www.example.com", "example:element");
    echo $element->lookupPrefix("http://www.example.com");
    // Output: example

    normalize()
    Description: Normalizes the current node by merging adjacent text nodes and removing empty text nodes.
    Example:

    $dom = new DOMDocument();
    $textNode = $dom->createTextNode("Hello");
    $space = $dom->createTextNode(" ");
    $otherTextNode = $dom->createTextNode("World!");
    $element = $dom->createElement("example");
    $element->appendChild($textNode);
    $element->appendChild($space);
    $element->appendChild($otherTextNode);
    $element->normalize();
    echo $dom->saveXML();
    // Output: <example>Hello World!</example>

    removeChild()
    Description: Removes a child node from the current node.
    Example:

    $dom = new DOMDocument();
    $parent = $dom->createElement("parent");
    $child = $dom->createElement("child");
    $parent->appendChild($child);
    $parent->removeChild($child);
    echo $dom->saveXML();
    // Output: <parent/>

    removeChild()
    Description: Removes a child node from the current node.
    Example:

    $dom = new DOMDocument();
    $parent = $dom->createElement("parent");
    $child = $dom->createElement("child");
    $parent->appendChild($child);
    $parent->removeChild($child);
    echo $dom->saveXML();
    // Output: <parent/>

    replaceChild()
    Description: Replaces a child node with another node.
    Example:

    $dom = new DOMDocument();
    $parent = $dom->createElement("parent");
    $child1 = $dom->createElement("child1");
    $child2 = $dom->createElement("child2");
    $parent->appendChild($child1);
    $parent->replaceChild($child2, $child1);
    echo $dom->saveXML();
    // Output: <parent><child2/></parent>

    DOMProcessingInstruction

    DOMProcessingInstruction __construct()
    Description: Constructs a new processing instruction. This is typically used to add instructions for applications like XML stylesheets.
    Example:

    $dom = new DOMDocument();
    $pi = $dom->createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"style.xsl\"");
    $dom->appendChild($pi);
    echo $dom->saveXML();
    // Output: <?xml-stylesheet type="text/xsl" href="style.xsl"?>

    DOMProcessingInstruction data()
    Description: Retrieves or sets the content of the processing instruction.
    Example:

    $dom = new DOMDocument();
    $pi = $dom->createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"style.xsl\"");
    $dom->appendChild($pi);
    echo $pi->data;
    // Output: type="text/xsl" href="style.xsl"

    DOMProcessingInstruction target()
    Description: Retrieves the target of the processing instruction, such as the application it is intended for.
    Example:

    DOMText

    PHP DOMText __construct() Function
    Description: Constructs a new DOMText object. A DOMText node is used to represent text within an element or attribute in the DOM.
    Example:

    $dom = new DOMDocument();
    $textNode = new DOMText("Hello, World!");
    $dom->appendChild($textNode);
    echo $dom->saveXML();
    // Output: Hello, World!

    PHP DOMText isElementContentWhitespace() Function
    Description: Checks if the text node contains only whitespace and is part of the element’s content.
    Example:

    $dom = new DOMDocument();
    $dom->loadXML("<root>   <child>Content</child>   </root>");
    $textNode = $dom->documentElement->firstChild;
    echo $textNode->isElementContentWhitespace() ? "Yes" : "No";
    // Output: Yes

    PHP DOMText isWhitespaceInElementContent() Function
    Description: An alias for isElementContentWhitespace(). Checks if the text node contains only whitespace and is part of the element’s content.
    Example:

    $dom = new DOMDocument();
    $dom->loadXML("<root>   <child>Content</child>   </root>");
    $textNode = $dom->documentElement->firstChild;
    echo $textNode->isWhitespaceInElementContent() ? "Yes" : "No";
    // Output: Yes

    PHP DOMText splitText() Function
    Description: Splits a text node into two at the specified offset. The original node contains the text before the offset, and a new node is created with the text after the offset.
    Example:

    $dom = new DOMDocument();
    $textNode = $dom->createTextNode("Hello, World!");
    $dom->appendChild($textNode);
    
    $newNode = $textNode->splitText(7);
    echo $textNode->wholeText . "\n"; // Output: Hello,
    echo $newNode->wholeText;        // Output: World!

    DOMXPath

    PHP DOMXPath __construct() Function
    Description: Creates a new DOMXPath object for querying and evaluating XPath expressions on a DOMDocument.

    $dom = new DOMDocument();
    $dom->loadXML("<root><item>Value</item></root>");
    $xpath = new DOMXPath($dom);
    echo "DOMXPath object created.";

    PHP DOMXPath evaluate() Function
    Description: Evaluates an XPath expression and returns the result. The result can be a DOMNodeList, a string, a number, or a boolean, depending on the expression.
    Example:

    $dom = new DOMDocument();
    $dom->loadXML("<root><item>Value</item></root>");
    $xpath = new DOMXPath($dom);
    $result = $xpath->evaluate("string(/root/item)");
    echo $result; // Output: Value

    PHP DOMXPath query() Function
    Description: Executes an XPath query and returns a DOMNodeList containing all nodes matching the expression.
    Example:

    $dom = new DOMDocument();
    $dom->loadXML("<root><item>Value1</item><item>Value2</item></root>");
    $xpath = new DOMXPath($dom);
    $nodes = $xpath->query("//item");
    
    foreach ($nodes as $node) {
        echo $node->nodeValue . "\n";
    }
    // Output:
    // Value1
    // Value2

    PHP DOMXPath registerNamespace() Function
    Description: Registers a namespace with a prefix for use in XPath queries.
    Example:

    $dom = new DOMDocument();
    $dom->loadXML('<root xmlns:ns="http://example.com"><ns:item>Value</ns:item></root>');
    $xpath = new DOMXPath($dom);
    $xpath->registerNamespace("ns", "http://example.com");
    $result = $xpath->evaluate("string(//ns:item)");
    echo $result; // Output: Value

    PHP DOMXPath registerPhpFunctions() Function
    Description: Enables PHP functions to be used within XPath expressions. By default, PHP functions are not available in XPath queries.
    Example:

    $dom = new DOMDocument();
    $dom->loadXML('<root><item>Value</item></root>');
    $xpath = new DOMXPath($dom);
    $xpath->registerPhpFunctions();
    $result = $xpath->evaluate("php:function('strtoupper', /root/item)");
    echo $result; // Output: VALUE

    DOM Functions

    PHP dom_import_simplexml() Function
    Description:The dom_import_simplexml() function converts a SimpleXMLElement object into a DOMElement object, allowing you to work with the node using the DOM extension methods.
    Example:

    // Create a SimpleXMLElement object
    $simpleXml = simplexml_load_string("<root><item>Value</item></root>");
    
    // Import the SimpleXMLElement into a DOMElement
    $domElement = dom_import_simplexml($simpleXml);
    
    if ($domElement) {
        echo $domElement->nodeName; // Output: root
    }
  • Ds\Vector Functions

    Ds\Vector Functions

    allocate()
    Description: Provides the custom size of the vector to allocate space.
    Example:

    $vector = new Vector();
    $vector->allocate(10);
    echo $vector->capacity();
    // Output: 10

    apply()
    Description: Updates all values in the array by applying the callback function to each value of the vector.
    Example:

    $vector = new Vector([1, 2, 3]);
    $vector->apply(fn($value) => $value * 2);
    print_r($vector->toArray());
    // Output: [2, 4, 6]

    capacity()
    Description: Returns the current capacity of the vector.
    Example:

    $vector = new Vector();
    echo $vector->capacity();
    // Output: 0

    clear()
    Description: Clears the vector elements by removing all the elements.
    Example:

    $vector = new Vector([1, 2, 3]);
    $vector->clear();
    echo $vector->isEmpty();
    // Output: 1 (true)

    __construct()
    Description: Creates a new instance.
    Example:

    $vector = new Vector([1, 2, 3]);
    print_r($vector->toArray());
    // Output: [1, 2, 3]

    contains()
    Description: Checks whether the vector contains the given value.
    Example:

    $vector = new Vector([1, 2, 3]);
    echo $vector->contains(2);
    // Output: 1 (true)

    copy()
    Description: Returns a shallow copy of the set.
    Example:

    $result = gmp_div_qr("10", "3");
    // Output: ([quotient => 3, remainder => 1])

    copy()
    Description: Creates a copy of the given vector.
    Example:

    $vector = new Vector([1, 2, 3]);
    $copy = $vector->copy();
    print_r($copy->toArray());
    // Output: [1, 2, 3]

    count()
    Description: Counts the number of elements in the vector.
    Example:

    $vector = new Vector([1, 2, 3]);
    echo $vector->count();
    // Output: 3

    filter()
    Description: Filters out elements that satisfy the condition defined in the callback function.
    Example:

    $vector = new Vector([1, 2, 3, 4]);
    $result = $vector->filter(fn($value) => $value > 2);
    print_r($result->toArray());
    // Output: [3, 4]

    find()
    Description: Finds the index of the element in the vector.
    Example:

    $vector = new Vector([1, 2, 3]);
    echo $vector->find(2);
    // Output: 1

    first()
    Description: Returns the first element in the vector.
    Example:

    $vector = new Vector([1, 2, 3]);
    echo $vector->first();
    // Output: 1

    get()
    Description: Returns the element at the given index.
    Example:

    $vector = new Vector([1, 2, 3]);
    echo $vector->get(1);
    // Output: 2

    insert()
    Description: Inserts the element into the vector at the given index.
    Example:

    $vector = new Vector([1, 3]);
    $vector->insert(1, 2);
    print_r($vector->toArray());
    // Output: [1, 2, 3]

    isEmpty()
    Description: Checks whether the vector is empty.
    Example:

    $vector = new Vector();
    echo $vector->isEmpty();
    // Output: 1 (true)

    join()
    Description: Joins elements of the vector into a string using the specified separator.
    Example:

    $vector = new Vector(["a", "b", "c"]);
    echo $vector->join(",");
    // Output: a,b,c

    jsonSerialize()
    Description: Returns elements that can be converted to JSON.
    Example:

    $vector = new Vector(["a", "b", "c"]);
    echo json_encode($vector);
    // Output: ["a","b","c"]

    last()
    Description: Returns the last element of the vector.
    Example:

    $vector = new Vector([1, 2, 3]);
    echo $vector->last();
    // Output: 3

    map()
    Description: Returns the result of a callback after applying it to each value in the vector.
    Example:

    $vector = new Vector([1, 2, 3]);
    $result = $vector->map(fn($value) => $value * 2);
    print_r($result->toArray());
    // Output: [2, 4, 6]

    merge()
    Description: Merges all the elements into the vector.
    Example:

    $vector = new Vector([1, 2]);
    $vector->merge([3, 4]);
    print_r($vector->toArray());
    // Output: [1, 2, 3, 4]

    pop()
    Description: Removes the last element of the vector and returns it.
    Example:

    $vector = new Vector([1, 2, 3]);
    echo $vector->pop();
    // Output: 3

    push()
    Description: Adds elements to the end of the vector.
    Example:

    $vector = new Vector([1, 2]);
    $vector->push(3);
    print_r($vector->toArray());
    // Output: [1, 2, 3]

    reduce()
    Description: Reduces the vector to a single value by applying operations in the callback function.
    Example:

    $vector = new Vector([1, 2, 3]);
    $result = $vector->reduce(fn($carry, $value) => $carry + $value, 0);
    echo $result;
    // Output: 6

    remove()
    Description: Removes and returns a value by index.
    Example:

    $vector = new Vector([1, 2, 3]);
    echo $vector->remove(1);
    // Output: 2

    reverse()
    Description: Reverses the vector elements in place.
    Example:

    $vector = new Vector([1, 2, 3]);
    $vector->reverse();
    print_r($vector->toArray());
    // Output: [3, 2, 1]

    rotate()
    Description: Rotates the array elements by a given number of rotations. Rotations happen in place.
    Example:

    $vector = new Vector([1, 2, 3, 4]);
    $vector->rotate(2);
    print_r($vector->toArray());
    // Output: [3, 4, 1, 2]

    set()
    Description: Sets the value in the vector at the given index.
    Example:

    $vector = new Vector([1, 2, 3]);
    $vector->set(1, 5);
    print_r($vector->toArray());
    // Output: [1, 5, 3]

    shift()
    Description: Removes the first element from the vector and returns it.
    Example:

    $vector = new Vector([1, 2, 3]);
    echo $vector->shift();
    // Output: 1

    slice()
    Description: Returns the sub-vector of the given vector.
    Example:

    $vector = new Vector([1, 2, 3, 4]);
    $subVector = $vector->slice(1, 3);
    print_r($subVector->toArray());
    // Output: [2, 3]

    sort()
    Description: Sorts the elements of the vector in place.
    Example:

    $vector = new Vector([3, 1, 2]);
    $vector->sort();
    print_r($vector->toArray());
    // Output: [1, 2, 3]
  • PHP SPL Data structures

    SplDoublyLinkedList Functions

    add()
    Description: Add a new value at the given index in the doubly linked list.
    Example:

    $list = new SplDoublyLinkedList();
    $list->add(0, "A");
    $list->add(1, "B");
    
    print_r($list);
    // Output: SplDoublyLinkedList Object ([0] => A [1] => B)

    bottom()
    Description: Peek the value of the node from the beginning of the doubly linked list.
    Example:

    $list = new SplDoublyLinkedList();
    $list->push("A");
    $list->push("B");
    
    echo $list->bottom();
    // Output: A

    count()
    Description: Count the number of elements present in a doubly linked list.
    Example:

    $list = new SplDoublyLinkedList();
    $list->push("A");
    $list->push("B");
    
    echo $list->count();
    // Output: 2

    push()
    Description: Push an element at the end of the doubly linked list.
    Example:

    $list = new SplDoublyLinkedList();
    $list->push("A");
    $list->push("B");
    
    print_r($list);
    // Output: SplDoublyLinkedList Object ([0] => A [1] => B)

    unshift()
    Description: Add an element at the beginning of the doubly linked list.
    Example:

    $list = new SplDoublyLinkedList();
    $list->push("B");
    $list->unshift("A");
    
    print_r($list);
    // Output: SplDoublyLinkedList Object ([0] => A [1] => B)

    top()
    Description: Return the value of the last (top) node in a doubly-linked list.
    Example:

    $list = new SplDoublyLinkedList();
    $list->push("A");
    $list->push("B");
    
    echo $list->top();
    // Output: B

    pop()
    Description: Pop the node from the end of the doubly linked list.
    Example:

    $list = new SplDoublyLinkedList();
    $list->push("A");
    $list->push("B");
    
    echo $list->pop();
    // Output: B

    isEmpty()
    Description: Check whether the doubly linked list is empty.
    Example:

    $list = new SplDoublyLinkedList();
    
    echo $list->isEmpty();
    // Output: 1 (true)

    rewind()
    Description: Rewind the iterator back to the start or beginning of the doubly linked list.
    Example:

    $list = new SplDoublyLinkedList();
    $list->push("A");
    $list->push("B");
    
    $list->rewind();
    echo $list->current();
    // Output: A

    shift()
    Description: Remove the first element from the doubly linked list and return it.
    Example:

    $list = new SplDoublyLinkedList();
    $list->push("A");
    $list->push("B");
    
    echo $list->shift();
    // Output: A

    add()
    Description: Add a new value at the given index in the doubly linked list.
    Example:

    $list = new SplDoublyLinkedList();
    $list->add(0, "A");
    $list->add(1, "B");
    
    print_r($list);
    // Output: SplDoublyLinkedList Object ([0] => A [1] => B)

    bottom()
    Description: Peek the value of the node from the beginning of the doubly linked list.
    Example:

    $list = new SplDoublyLinkedList();
    $list->push("A");
    $list->push("B");
    
    echo $list->bottom();
    // Output: A

    count()
    Description: Count the number of elements present in a doubly linked list.
    Example:

    $list = new SplDoublyLinkedList();
    $list->push("A");
    $list->push("B");
    
    echo $list->count();
    // Output: 2

    SplFixedArray Functions

    count()
    Description: Return the number of elements in the SplFixedArray.
    Example:

    $array = new SplFixedArray(5);
    echo $array->count();
    // Output: 5

    current()
    Description: Get the current entry of the array iterator.
    Example:

    $array = new SplFixedArray(3);
    $array[0] = "A";
    $array[1] = "B";
    
    $array->rewind();
    echo $array->current();
    // Output: A

    getSize()
    Description: Get the size of the SplFixedArray.
    Example:

    $array = new SplFixedArray(4);
    echo $array->getSize();
    // Output: 4

    key()
    Description: Get the key of the current iterator index.
    Example:

    $array = new SplFixedArray(3);
    $array[0] = "A";
    
    $array->rewind();
    echo $array->key();
    // Output: 0

    next()
    Description: Move the iterator to the next entry.
    Example:

    $array = new SplFixedArray(3);
    $array[0] = "A";
    $array[1] = "B";
    
    $array->rewind();
    $array->next();
    echo $array->current();
    // Output: B

    offsetExists()
    Description: Check if the provided index exists in the SplFixedArray.
    Example:

    $array = new SplFixedArray(3);
    echo $array->offsetExists(2);
    // Output: 1 (true)

    offsetGet()
    Description: Get the value at the specified index in the SplFixedArray.
    Example:

    $array = new SplFixedArray(3);
    $array[1] = "B";
    echo $array->offsetGet(1);
    // Output: B

    offsetUnset()
    Description: Unset the value of the specified index in the SplFixedArray.
    Example:

    $array = new SplFixedArray(3);
    $array[1] = "B";
    $array->offsetUnset(1);
    
    print_r($array);
    // Output: SplFixedArray Object ([0] => , [1] => , [2] => )

    rewind()
    Description: Rewind the array iterator back to the start.
    Example:

    $array = new SplFixedArray(3);
    $array[0] = "A";
    $array[1] = "B";
    
    $array->next();
    $array->rewind();
    echo $array->current();
    // Output: A

    rewind()
    Description: Rewind the array iterator back to the start.
    Example:

    $array = new SplFixedArray(3);
    $array[0] = "A";
    $array[1] = "B";
    
    $array->next();
    $array->rewind();
    echo $array->current();
    // Output: A

    List of PHP SPL SplObjectStorage Functions

    addAll()
    Description: Add elements from another SplObjectStorage to the current one.
    Example:

    $storage1 = new SplObjectStorage();
    $storage2 = new SplObjectStorage();
    
    $obj1 = new stdClass();
    $obj2 = new stdClass();
    $obj3 = new stdClass();
    
    $storage1->attach($obj1);
    $storage2->attach($obj2);
    $storage2->attach($obj3);
    
    $storage1->addAll($storage2);
    echo $storage1->count();
    // Output: 3

    attach()
    Description: Add an object to the SplObjectStorage.
    Example:

    $storage = new SplObjectStorage();
    $obj = new stdClass();
    
    $storage->attach($obj);
    echo $storage->count();
    // Output: 1

    contains()
    Description: Check if a specific object exists in the SplObjectStorage.
    Example:

    $storage = new SplObjectStorage();
    $obj = new stdClass();
    
    $storage->attach($obj);
    echo $storage->contains($obj);
    // Output: 1 (true)

    count()
    Description: Get the number of objects in the SplObjectStorage.
    Example:

    $storage = new SplObjectStorage();
    echo $storage->count();
    // Output: 0

    current()
    Description: Get the current object in the iterator.
    Example:

    $storage = new SplObjectStorage();
    $obj1 = new stdClass();
    $obj2 = new stdClass();
    
    $storage->attach($obj1);
    $storage->attach($obj2);
    
    $storage->rewind();
    print_r($storage->current());
    // Output: Object(stdClass)

    detach()
    Description: Remove a specific object from the SplObjectStorage.
    Example:

    $storage = new SplObjectStorage();
    $obj = new stdClass();
    
    $storage->attach($obj);
    $storage->detach($obj);
    echo $storage->count();
    // Output: 0

    getInfo()
    Description: Retrieve the data associated with the current object.
    Example:

    $storage = new SplObjectStorage();
    $obj = new stdClass();
    
    $storage->attach($obj, "data");
    echo $storage->getInfo();
    // Output: data

    key()
    Description: Get the current iterator index.
    Example:

    $storage = new SplObjectStorage();
    $obj1 = new stdClass();
    $obj2 = new stdClass();
    
    $storage->attach($obj1);
    $storage->attach($obj2);
    
    $storage->rewind();
    echo $storage->key();
    // Output: 0

    next()
    Description: Move the iterator to the next object.
    Example:

    $storage = new SplObjectStorage();
    $obj1 = new stdClass();
    $obj2 = new stdClass();
    
    $storage->attach($obj1);
    $storage->attach($obj2);
    
    $storage->rewind();
    $storage->next();
    print_r($storage->current());
    // Output: Object(stdClass)

    offsetExists()
    Description: Check if an object exists in the SplObjectStorage.
    Example:

    $storage = new SplObjectStorage();
    $obj = new stdClass();
    
    $storage->attach($obj);
    echo $storage->offsetExists($obj);
    // Output: 1 (true)

    offsetGet()
    Description: Retrieve the data associated with the specified object.
    Example:

    $storage = new SplObjectStorage();
    $obj = new stdClass();
    
    $storage->attach($obj, "info");
    echo $storage->offsetGet($obj);
    // Output: info

    offsetSet()
    Description: Set data for a specific object in the storage.
    Example:

    $storage = new SplObjectStorage();
    $obj = new stdClass();
    
    $storage->offsetSet($obj, "info");
    echo $storage->getInfo();
    // Output: info

    offsetUnset()
    Description: Unset a specific object from the storage.
    Example:

    $storage = new SplObjectStorage();
    $obj = new stdClass();
    
    $storage->attach($obj);
    $storage->offsetUnset($obj);
    echo $storage->count();
    // Output: 0

    List of PHP SPL SplObjectStorage Functions

    __construct()
    Description: Constructs a queue that is implemented using a doubly-linked list.
    Example:

    $queue = new SplQueue();
    echo get_class($queue);
    // Output: SplQueue

    dequeue()
    Description: Removes and returns the node from the front of the queue.
    Example:

    $queue = new SplQueue();
    $queue->enqueue("First");
    $queue->enqueue("Second");
    
    echo $queue->dequeue();
    // Output: First

    enqueue()
    Description: Adds an element to the back of the queue.
    Example:

    $queue = new SplQueue();
    $queue->enqueue("First");
    $queue->enqueue("Second");
    
    echo $queue->bottom();
    // Output: First

    bottom()
    Description: Returns the value of the node at the bottom (front) of the queue without removing it.
    Example:

    $queue = new SplQueue();
    $queue->enqueue("First");
    $queue->enqueue("Second");
    
    echo $queue->bottom();
    // Output: First
  • Ds\Sequence Functions

    Ds\Deque Functions

    allocate()
    Description: This is used to allocate memory as specified in the argument.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    $sequence->allocate(10);
    
    echo $sequence->capacity();
    // Output: 10

    apply()
    Description: Update the values of the Deque by performing operations as defined by the callback function.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    $sequence->apply(fn($value) => $value * 2);
    
    print_r($sequence);
    // Output: Ds\Vector Object ([0] => 2 [1] => 4 [2] => 6)

    capacity()
    Description: Return the current capacity of the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2]);
    echo $sequence->capacity();
    // Output: 2

    contains()
    Description: Check whether the given value exists in the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    echo $sequence->contains(2);
    // Output: 1 (true)

    filter()
    Description: Create a new sequence using a filter function.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3, 4]);
    $filtered = $sequence->filter(fn($value) => $value % 2 == 0);
    
    print_r($filtered);
    // Output: Ds\Vector Object ([0] => 2 [1] => 4)

    find()
    Description: Find the index of a value in the sequence. Returns false if not found.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    echo $sequence->find(3);
    // Output: 2

    first()
    Description: Return the first element in the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    echo $sequence->first();
    // Output: 1

    get()
    Description: Return the value at the given index.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    echo $sequence->get(1);
    // Output: 2

    insert()
    Description: Insert a value at the given index in the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2, 4]);
    $sequence->insert(2, 3);
    
    print_r($sequence);
    // Output: Ds\Vector Object ([0] => 1 [1] => 2 [2] => 3 [3] => 4)

    join()
    Description: Join all values in the sequence into a string.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    echo $sequence->join(", ");
    // Output: 1, 2, 3

    last()
    Description: Return the last element in the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    echo $sequence->last();
    // Output: 3

    map()
    Description: Return the result of applying a callback function to each value in the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    $mapped = $sequence->map(fn($value) => $value * 2);
    
    print_r($mapped);
    // Output: Ds\Vector Object ([0] => 2 [1] => 4 [2] => 6)

    merge()
    Description: Returns a sequence after adding all given values to the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2]);
    $merged = $sequence->merge([3, 4, 5]);
    
    print_r($merged);
    // Output: Ds\Vector Object ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5)

    pop()
    Description: Removes and returns the last value from the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    echo $sequence->pop();
    // Output: 3
    
    print_r($sequence);
    // Output: Ds\Vector Object ([0] => 1 [1] => 2)

    push()
    Description: Adds values to the end of the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2]);
    $sequence->push(3, 4);
    
    print_r($sequence);
    // Output: Ds\Vector Object ([0] => 1 [1] => 2 [2] => 3 [3] => 4)

    reduce()
    Description: Reduce the sequence to a single value using a callback function.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3, 4]);
    $result = $sequence->reduce(fn($carry, $value) => $carry + $value, 0);
    
    echo $result;
    // Output: 10

    remove()
    Description: Remove and return the value at a given index.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    echo $sequence->remove(1);
    // Output: 2
    
    print_r($sequence);
    // Output: Ds\Vector Object ([0] => 1 [1] => 3)

    reverse()
    Description: Reverse the sequence in place.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    $sequence->reverse();
    
    print_r($sequence);
    // Output: Ds\Vector Object ([0] => 3 [1] => 2 [2] => 1)

    reversed()
    Description: Return a reversed copy of the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    $reversed = $sequence->reversed();
    
    print_r($reversed);
    // Output: Ds\Vector Object ([0] => 3 [1] => 2 [2] => 1)

    rotate()
    Description: Rotate the sequence elements by a given number of rotations.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3, 4]);
    $sequence->rotate(2);
    
    print_r($sequence);
    // Output: Ds\Vector Object ([0] => 3 [1] => 4 [2] => 1 [3] => 2)

    set()
    Description: Update the value at a given index in the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    $sequence->set(1, 42);
    
    print_r($sequence);
    // Output: Ds\Vector Object ([0] => 1 [1] => 42 [2] => 3)

    shift()
    Description: Remove and return the first element of the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    echo $sequence->shift();
    // Output: 1
    
    print_r($sequence);
    // Output: Ds\Vector Object ([0] => 2 [1] => 3)

    slice()
    Description: Return a sub-sequence containing elements within the specified range.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3, 4, 5]);
    $sliced = $sequence->slice(1, 3);
    
    print_r($sliced);
    // Output: Ds\Vector Object ([0] => 2 [1] => 3 [2] => 4)

    sort()
    Description: Sort the sequence elements in place.
    Example:

    $sequence = new \Ds\Vector([3, 1, 2]);
    $sequence->sort();
    
    print_r($sequence);
    // Output: Ds\Vector Object ([0] => 1 [1] => 2 [2] => 3)

    sorted()
    Description: Return a sorted copy of the sequence.
    Example:

    $sequence = new \Ds\Vector([3, 1, 2]);
    $sorted = $sequence->sorted();
    
    print_r($sorted);
    // Output: Ds\Vector Object ([0] => 1 [1] => 2 [2] => 3)

    sum()
    Description: Return the sum of all values in the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3, 4, 5]);
    echo $sequence->sum();
    // Output: 15

    toArray()
    Description: Convert the sequence into an array.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    $array = $sequence->toArray();
    
    print_r($array);
    // Output: Array ( [0] => 1 [1] => 2 [2] => 3 )

    unshift()
    Description: Add values to the beginning of the sequence.
    Example:

    $sequence = new \Ds\Vector([2, 3]);
    $sequence->unshift(1);
    
    print_r($sequence);
    // Output: Ds\Vector Object ([0] => 1 [1] => 2 [2] => 3)

    apply()
    Description: Update all values in the sequence by applying a callback function to each value.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    $sequence->apply(fn($value) => $value * 2);
    
    print_r($sequence);
    // Output: Ds\Vector Object ([0] => 2 [1] => 4 [2] => 6)

    filter()
    Description: Create a new sequence containing only the elements that match the callback function’s condition.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3, 4, 5]);
    $filtered = $sequence->filter(fn($value) => $value % 2 === 0);
    
    print_r($filtered);
    // Output: Ds\Vector Object ([0] => 2 [1] => 4)

    find()
    Description: Find the index of the first occurrence of a value in the sequence.
    Example:

    $sequence = new \Ds\Vector([10, 20, 30, 40]);
    echo $sequence->find(30);
    // Output: 2

    first()
    Description: Return the first value in the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    echo $sequence->first();
    // Output: 1

    last()
    Description: Return the last value in the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    echo $sequence->last();
    // Output: 3

    contains()
    Description: Check if a sequence contains a given value.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    echo $sequence->contains(2);
    // Output: 1 (true)

    map()
    Description: Return a new sequence by applying a callback function to each value in the sequence.
    Example:

    $sequence = new \Ds\Vector([1, 2, 3]);
    $mapped = $sequence->map(fn($value) => $value * 10);
    
    print_r($mapped);
    // Output: Ds\Vector Object ([0] => 10 [1] => 20 [2] => 30)

    rotate()
    Description: Rotate the sequence elements by a given number of rotations (positive or negative).
    Example:

    $sequence = new \Ds\Vector([1, 2, 3, 4]);
    $sequence->rotate(-2);
    
    print_r($sequence);
    // Output: Ds\Vector Object ([0] => 3 [1] => 4 [2] => 1 [3] => 2)
  • Ds\Deque Functions

    Ds\Deque Functions

    allocate()
    Description: Allocate memory for a PriorityQueue class instance.
    Example:

    $deque = new \Ds\Deque();
    $deque->allocate(10);
    
    echo $deque->capacity();
    // Output: 10

    capacity()
    Description: Check the current capacity of a PriorityQueue instance.
    Example:

    $deque = new \Ds\Deque([1, 2, 3]);
    $deque->apply(function ($value) {
        return $value * 2;
    });
    
    print_r($deque);
    // Output: Ds\Deque Object ([0] => 2 [1] => 4 [2] => 6)

    capacity()
    Description: Get the current capacity of the Deque.
    Example:

    $deque = new \Ds\Deque();
    $deque->allocate(20);
    
    echo $deque->capacity();
    // Output: 20

    clear()
    Description: Clear the Deque by removing all elements.
    Example:

    $deque = new \Ds\Deque([1, 2, 3]);
    $deque->clear();
    
    echo $deque->isEmpty();
    // Output: 1 (true)

    copy()
    Description: Return a shallow copy of the Deque.
    Example:

    $deque = new \Ds\Deque([1, 2, 3]);
    $copy = $deque->copy();
    
    print_r($copy);
    // Output: Ds\Deque Object ([0] => 1 [1] => 2 [2] => 3)

    count()
    Description: Get the number of elements in the Deque.
    Examaple:

    $deque = new \Ds\Deque([1, 2, 3]);
    
    echo $deque->count();
    // Output: 3

    filter()
    Description: Filter out the elements from the Deque based on the operation defined in the callback function.
    Example:

    $deque = new \Ds\Deque([1, 2, 3, 4, 5]);
    $filtered = $deque->filter(function ($value) {
        return $value % 2 === 0;
    });
    
    print_r($filtered);
    // Output: Ds\Deque Object ([0] => 2 [1] => 4)

    find()
    Description: Find the index of the element in the Deque if the element is found.
    Example:

    $deque = new \Ds\Deque(["a", "b", "c"]);
    
    echo $deque->find("b");
    // Output: 1

    first()
    Description: Returns the first value in the Deque if it is not empty.
    Example:

    $deque = new \Ds\Deque([1, 2, 3]);
    
    echo $deque->first();
    // Output: 1

    get()
    Description: Return the value at the given index.
    Example:

    $deque = new \Ds\Deque([1, 2, 3]);
    
    echo $deque->get(1);
    // Output: 2

    insert()
    Description: Insert the value at the given index in the Deque.
    Example:

    $deque = new \Ds\Deque([1, 2, 3]);
    $deque->insert(1, 99);
    
    print_r($deque);
    // Output: Ds\Deque Object ([0] => 1 [1] => 99 [2] => 2 [3] => 3)

    toArray()
    Description: Convert a PriorityQueue into an associative array.
    Example:

    $deque = new \Ds\Deque();
    
    echo $deque->isEmpty();
    // Output: 1 (true)

    join()
    Description: Join all values in the Deque as a string.
    Example:

    $deque = new \Ds\Deque([1, 2, 3]);
    
    echo $deque->join(", ");
    // Output: 1, 2, 3

    last()
    Description: Return the last element of the Deque if it is not empty.
    Example:

    $deque = new \Ds\Deque([1, 2, 3]);
    
    echo $deque->last();
    // Output: 3

    map()
    Description: Returns the result of applying a callback to each value in the Deque.
    Example:

    $deque = new \Ds\Deque([1, 2, 3]);
    $mapped = $deque->map(function ($value) {
        return $value * 10;
    });
    
    print_r($mapped);
    // Output: Ds\Deque Object ([0] => 10 [1] => 20 [2] => 30)

    merge()
    Description: Returns the result of adding all given values to the Deque.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push(10, 1);
    $pq->push(20, 2);
    $pq->push(30, 3);
    
    $sum = array_reduce($pq->toArray(), function ($carry, $item) {
        return $carry + $item[0]; // Sum all values
    }, 0);
    
    echo $sum;
    // Output: 60

    reversed()
    Description: Get a reversed version of the PriorityQueue.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $reversed = array_reverse($pq->toArray());
    
    print_r($reversed);
    // Output: Array ( [0] => One [1] => Two [2] => Three )

    contains()
    Description: Check whether a PriorityQueue contains a specific value.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    
    echo $pq->contains("One") ? "Yes" : "No";
    // Output: Yes

    merge()
    Description: Merge another collection into the PriorityQueue and maintain priorities.
    Example:

    $pq1 = new \Ds\PriorityQueue();
    $pq1->push("One", 1);
    $pq1->push("Two", 2);
    
    $pq2 = new \Ds\PriorityQueue();
    $pq2->push("Three", 3);
    $pq2->push("Four", 4);
    
    foreach ($pq2->toArray() as $item) {
        $pq1->push($item[0], $item[1]);
    }
    
    print_r($pq1->toArray());
    // Output: Array ( [0] => Four [1] => Three [2] => Two [3] => One )

    sort()
    Description: Sort elements in-place by their priorities in descending order.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 3);
    $pq->push("Two", 1);
    $pq->push("Three", 2);
    
    $sorted = $pq->toArray();
    usort($sorted, function ($a, $b) {
        return $b[1] - $a[1];
    });
    
    print_r($sorted);
    // Output: Array ( [0] => One [1] => Three [2] => Two )

    find()
    Description: Find and return an element in the PriorityQueue by a condition.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $found = array_filter($pq->toArray(), function ($item) {
        return $item[1] === 2; // Find item with priority 2
    });
    
    print_r($found);
    // Output: Array ( [0] => Two )

    splice()
    Description: Remove and return a subset of elements from the PriorityQueue.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $subset = array_slice($pq->toArray(), 1, 2);
    
    print_r($subset);
    // Output: Array ( [0] => Two [1] => One )

    reverse()
    Description: Reverse the order of elements in a PriorityQueue.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $reversed = array_reverse($pq->toArray());
    
    print_r($reversed);
    // Output: Array ( [0] => One [1] => Two [2] => Three )

    maxPriority()
    Description: Find the maximum priority present in the PriorityQueue.
    Example:

    $deque = new \Ds\Deque([1, 2, 3]);
    echo $deque->shift();
    // Output: 1
    
    print_r($deque);
    // Output: Ds\Deque Object ([0] => 2 [1] => 3)

    slice()
    Description: Return a sub-Deque containing elements within the specified index range.
    Example:

    $deque = new \Ds\Deque([1, 2, 3, 4, 5]);
    $sliced = $deque->slice(1, 3);
    
    print_r($sliced);
    // Output: Ds\Deque Object ([0] => 2 [1] => 3 [2] => 4)

    sort()
    Description: Sort the Deque in place by arranging elements in increasing order.
    Example:

    $deque = new \Ds\Deque([3, 1, 2]);
    $deque->sort();
    
    print_r($deque);
    // Output: Ds\Deque Object ([0] => 1 [1] => 2 [2] => 3)

    sorted()
    Description: Return a copy of the Deque with elements sorted in ascending order.
    Example:

    $deque = new \Ds\Deque([3, 1, 2]);
    $sorted = $deque->sorted();
    
    print_r($sorted);
    // Output: Ds\Deque Object ([0] => 1 [1] => 2 [2] => 3)

    sum()
    Description: Return the sum of all elements in the Deque.
    Example:

    $deque = new \Ds\Deque([1, 2, 3]);
    
    echo $deque->sum();
    // Output: 6

    toArray()
    Description: Convert the Deque to an array.
    Example:

    $deque = new \Ds\Deque([1, 2, 3]);
    $array = $deque->toArray();
    
    print_r($array);
    // Output: Array ([0] => 1 [1] => 2 [2] => 3)

    unshift()
    Description: Add a value to the front of the Deque.
    Example:

    $deque = new \Ds\Deque([2, 3]);
    $deque->unshift(1);
    
    print_r($deque);
    // Output: Ds\Deque Object ([0] => 1 [1] => 2 [2] => 3)

    filter()
    Description: Filter out the elements from the Deque based on the condition defined in the callback function.
    Example:

    find()
    Description: Find the index of the specified element in the Deque. Returns false if not found.
    Example:

    $deque = new \Ds\Deque([1, 2, 3, 4, 5]);
    $filtered = $deque->filter(fn($value) => $value % 2 == 0);
    
    print_r($filtered);
    // Output: Ds\Deque Object ([0] => 2 [1] => 4)

    first()
    Description: Return the first element in the Deque.
    Example:

    $deque = new \Ds\Deque([1, 2, 3, 4]);
    echo $deque->find(3);
    // Output: 2

    first()
    Description: Return the first element in the Deque.
    Example:

    $deque = new \Ds\Deque([1, 2, 3]);
    echo $deque->first();
    // Output: 1
    $deque = new \Ds\Deque([1, 2, 3]);
    echo $deque->first();
    // Output: 1
  • Ds\PriorityQueue Functions

    Basic Ds\PriorityQueue Functions

    allocate()
    Description: Allocate memory for a PriorityQueue class instance.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->allocate(10);
    echo $pq->capacity();
    // Output: 10

    capacity()
    Description: Check the current capacity of a PriorityQueue instance.
    Example:

    $pq = new \Ds\PriorityQueue();
    echo $pq->capacity();
    // Output: 10 (default or allocated capacity)

    clear()
    Description: Clear all of the elements from a PriorityQueue instance.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->clear();
    echo $pq->count();
    // Output: 0

    clear()
    Description: Removes all values from the set.
    Example:

    $set = new \Ds\Set([1, 2, 3]);
    $set->clear();
    print_r($set);
    // Output: Ds\Set Object ()

    copy()
    Description: Create a shallow copy of a particular PriorityQueue instance.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $copy = $pq->copy();
    print_r($copy->toArray());
    // Output: Array ( [0] => Two [1] => One ) (based on priority)

    count()
    Description: Get the count of elements present in a PriorityQueue instance.
    Example:

    $set = new \Ds\Set([1, 2, 3]);
    var_dump($set->contains(2));
    // Output: (bool true)

    copy()
    Description: Returns a shallow copy of the set.
    Example:

    $result = gmp_div_qr("10", "3");
    // Output: ([quotient => 3, remainder => 1])

    count()
    Description: Counts the number of values in the set.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    echo $pq->count();
    // Output: 2

    peek()
    Description: Get the value present at the front of a PriorityQueue.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    echo $pq->peek();
    // Output: Two (highest priority)

    pop()
    Description: Remove and return the value present at the top of the PriorityQueue.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    echo $pq->pop();
    // Output: Two

    push()
    Description: Push or insert values in a PriorityQueue instance with a given priority.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    print_r($pq->toArray());
    // Output: Array ( [0] => Two [1] => One ) (based on priority)

    toArray()
    Description: Convert a PriorityQueue into an associative array.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    print_r($pq->toArray());
    // Output: Array ( [0] => Two [1] => One )

    union()
    Description: Create a new PriorityQueue that combines elements from two PriorityQueue instances.
    Example:

    $pq1 = new \Ds\PriorityQueue();
    $pq1->push("One", 1);
    $pq1->push("Two", 2);
    
    $pq2 = new \Ds\PriorityQueue();
    $pq2->push("Three", 3);
    $pq2->push("Four", 4);
    
    $union = new \Ds\PriorityQueue();
    
    foreach ($pq1 as $item) {
        $union->push($item[0], $item[1]);
    }
    foreach ($pq2 as $item) {
        $union->push($item[0], $item[1]);
    }
    
    print_r($union->toArray());
    // Output: Array ( [0] => Four [1] => Three [2] => Two [3] => One )

    intersect()
    Description: Create a new PriorityQueue containing only the common elements of two PriorityQueue instances.
    Example:

    $pq1 = new \Ds\PriorityQueue();
    $pq1->push("One", 1);
    $pq1->push("Two", 2);
    
    $pq2 = new \Ds\PriorityQueue();
    $pq2->push("Two", 2);
    $pq2->push("Three", 3);
    
    $intersection = [];
    foreach ($pq1 as $item1) {
        foreach ($pq2 as $item2) {
            if ($item1[0] === $item2[0] && $item1[1] === $item2[1]) {
                $intersection[] = $item1;
            }
        }
    }
    
    print_r($intersection);
    // Output: Array ( [0] => Array ( [0] => Two [1] => 2 ) )

    filter()
    Description: Filter elements of a PriorityQueue based on a callback function.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $filtered = array_filter($pq->toArray(), function ($item) {
        return $item[1] > 1; // Keep elements with priority > 1
    });
    
    print_r($filtered);
    // Output: Array ( [0] => Two [1] => Three )

    reduce()
    Description: Reduce the elements of the PriorityQueue to a single value using a callback function.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push(10, 1);
    $pq->push(20, 2);
    $pq->push(30, 3);
    
    $sum = array_reduce($pq->toArray(), function ($carry, $item) {
        return $carry + $item[0]; // Sum all values
    }, 0);
    
    echo $sum;
    // Output: 60

    reversed()
    Description: Get a reversed version of the PriorityQueue.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $reversed = array_reverse($pq->toArray());
    
    print_r($reversed);
    // Output: Array ( [0] => One [1] => Two [2] => Three )

    contains()
    Description: Check whether a PriorityQueue contains a specific value.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    
    echo $pq->contains("One") ? "Yes" : "No";
    // Output: Yes

    merge()
    Description: Merge another collection into the PriorityQueue and maintain priorities.
    Example:

    $pq1 = new \Ds\PriorityQueue();
    $pq1->push("One", 1);
    $pq1->push("Two", 2);
    
    $pq2 = new \Ds\PriorityQueue();
    $pq2->push("Three", 3);
    $pq2->push("Four", 4);
    
    foreach ($pq2->toArray() as $item) {
        $pq1->push($item[0], $item[1]);
    }
    
    print_r($pq1->toArray());
    // Output: Array ( [0] => Four [1] => Three [2] => Two [3] => One )

    sort()
    Description: Sort elements in-place by their priorities in descending order.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 3);
    $pq->push("Two", 1);
    $pq->push("Three", 2);
    
    $sorted = $pq->toArray();
    usort($sorted, function ($a, $b) {
        return $b[1] - $a[1];
    });
    
    print_r($sorted);
    // Output: Array ( [0] => One [1] => Three [2] => Two )

    find()
    Description: Find and return an element in the PriorityQueue by a condition.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $found = array_filter($pq->toArray(), function ($item) {
        return $item[1] === 2; // Find item with priority 2
    });
    
    print_r($found);
    // Output: Array ( [0] => Two )

    splice()
    Description: Remove and return a subset of elements from the PriorityQueue.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $subset = array_slice($pq->toArray(), 1, 2);
    
    print_r($subset);
    // Output: Array ( [0] => Two [1] => One )

    reverse()
    Description: Reverse the order of elements in a PriorityQueue.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $reversed = array_reverse($pq->toArray());
    
    print_r($reversed);
    // Output: Array ( [0] => One [1] => Two [2] => Three )

    maxPriority()
    Description: Find the maximum priority present in the PriorityQueue.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $maxPriority = max(array_column($pq->toArray(), 1));
    
    echo $maxPriority;
    // Output: 3

    minPriority()
    Description: Find the minimum priority present in the PriorityQueue.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $minPriority = min(array_column($pq->toArray(), 1));
    
    echo $minPriority;
    // Output: 1

    extractWithPriority()
    Description: Extract all elements with a specific priority.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Another One", 1);
    
    $priorityToExtract = 1;
    $extracted = array_filter($pq->toArray(), function ($item) use ($priorityToExtract) {
        return $item[1] === $priorityToExtract;
    });
    
    print_r($extracted);
    // Output: Array ( [0] => One [1] => Another One )

    priorities()
    Description: Get a list of all unique priorities in the PriorityQueue.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    $pq->push("Another One", 1);
    
    $uniquePriorities = array_unique(array_column($pq->toArray(), 1));
    
    print_r($uniquePriorities);
    // Output: Array ( [0] => 1 [1] => 2 [2] => 3 )

    mergeWithPriorityOverride()
    Description: Merge two PriorityQueue instances, overriding the priority of duplicate elements.
    Example:

    $pq1 = new \Ds\PriorityQueue();
    $pq1->push("One", 1);
    $pq1->push("Two", 2);
    
    $pq2 = new \Ds\PriorityQueue();
    $pq2->push("Two", 5);
    $pq2->push("Three", 3);
    
    $merged = [];
    foreach ($pq1->toArray() as $item) {
        $merged[$item[0]] = $item[1];
    }
    foreach ($pq2->toArray() as $item) {
        $merged[$item[0]] = $item[1]; // Override priority if the key exists
    }
    
    $result = new \Ds\PriorityQueue();
    foreach ($merged as $value => $priority) {
        $result->push($value, $priority);
    }
    
    print_r($result->toArray());
    // Output: Array ( [0] => Two [1] => Three [2] => One )

    filterByPriorityRange()
    Description: Filter elements with priorities within a given range.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $rangeStart = 1;
    $rangeEnd = 2;
    
    $filtered = array_filter($pq->toArray(), function ($item) use ($rangeStart, $rangeEnd) {
        return $item[1] >= $rangeStart && $item[1] <= $rangeEnd;
    });
    
    print_r($filtered);
    // Output: Array ( [0] => One [1] => Two )

    topN()
    Description: Retrieve the top N elements based on priority.
    Example:

    $pq = new \Ds\PriorityQueue();
    $pq->push("One", 1);
    $pq->push("Two", 2);
    $pq->push("Three", 3);
    
    $topN = 2;
    $sorted = $pq->toArray();
    usort($sorted, function ($a, $b) {
        return $b[1] - $a[1];
    });
    
    print_r(array_slice($sorted, 0, $topN));
    // Output: Array ( [0] => Three [1] => Two )